用gcc链接库:参数顺序 [英] Linking libraries with gcc: order of arguments

查看:78
本文介绍了用gcc链接库:参数顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将我的Ubuntu发行版升级到11.10后,我开始发现gcc出现奇怪的链接器行为.我可以通过将我的-l参数移到gcc命令的末尾来解决该问题(我的问题类似于

As soon as I upgraded my Ubuntu distro to 11.10, I started seeing strange linker behavior with gcc. I was able to fix the problem by moving my -l arguments to the end of the gcc command (my problem was similar to the one described in this thread, and the proposed solution worked for me...thanks!).

我的问题是...为什么我现在才有这个问题?我已经在OS X和Ubuntu上开发和测试此代码一段时间了:我不知道-l命令应该放在.c文件之后,但是即使这样,以前也从未给我带来问题.我猜想它与GCC的版本比Ubuntu的发行版更多.

My question is...why did I have this problem only now? I've been developing and testing this code on OS X and Ubuntu for a while: I never knew that -l commands are supposed to go after your .c files, but even so, this never gave me problems before. I'm guessing it has more to do with the version of GCC than the Ubuntu release version.

这个较新的版本是否比较早的版本更严格地执行了此要求?

Is this newer version simply enforcing this requirement more strictly than earlier versions?

推荐答案

对于gcc以及其他编译器(例如clang),链接器命令参数的顺序确实很重要. 根据经验,编写链接器命令时,我将使用以下顺序:

With gcc but also other compilers (e.g. clang), the order of linker command arguments does matter. As a rule of thumb, I would use the following order when composing the linker command:

  1. 目标文件(* .o)
  2. 静态库(* .a)
  3. 共享库(* .so)

共享库的顺序也很重要.如果libfoo.so依赖libbar.so,则应在-lbar之前列出-lfoo.

The order of shared libraries does matter as well. If libfoo.so depends on libbar.so, you should list -lfoo before -lbar.

如果您不知道确切的依赖关系,这可能会变得非常复杂.在Linux上执行以下命令可能会有所帮助:

This can get quite complex if you don't know the exact dependencies. The following command on linux could help:

ldd /path/to/libfoo.so

这列出了libfoo.so所依赖的所有共享库.

This lists all shared libs on which libfoo.so depends.

关于您的问题,为什么这个问题随您的特定gcc版本而出现,很难不知道您的应用程序需要哪个库.但是,如果您按照上述方法应用该命令,则该命令应适用于旧版本和较新的gcc版本.

As to your question why this problem popped up with your particular gcc version, it's hard to tell without knowing which libs your application requires. But if you apply the order like I described above, it should work for both older and newer gcc versions.

提示:如果正确使用CMake,则可以为您处理所有依赖项...

Hint: CMake, if used correctly, can handle all that dependency stuff for you...

这篇关于用gcc链接库:参数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆