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

查看:38
本文介绍了使用 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天全站免登陆