【问题标题】:G++ can't link in some libraries, but using ld separately it finds librariesG++ 无法链接某些库,但单独使用 ld 会找到库
【发布时间】:2015-02-12 17:25:20
【问题描述】:

在 Ubuntu Linux 机器上,g++ 似乎没有像应有的那样链接库。我无法提供完整的源代码,但本质上它是一个创建 pthread 的小程序。它在另外两台 Debian 机器上编译得很好,但在 Ubuntu 机器上它抱怨对 pthread_create 的未定义引用。

命令行是这样的:

g++ -I. -lpthread source_code.cpp -o program

为了调试它,我在 strace 下运行了 g++ 以查看它是如何查找 libpthread 的。当我这样做时,我没有看到任何对 libpthread 的引用。就好像链接器甚至没有尝试搜索库。在确实编译的机器上,当它在文件系统中搜索库时,我看到了几个对 open() 的调用。

当我单独运行 ld 时,它似乎发现 libpthread 没有问题,并且 strace 输出确认它正在按应有的方式搜索库。我像这样单独运行 ld:

user@machine:~/src$ ld -lpthread
ld: warning: cannot find entry symbol _start; not setting start address

当 ld 本身似乎可以正常搜索库时,为什么会导致 g++ 无法正确搜索文件系统?有点难倒这一刻。

谢谢!

【问题讨论】:

  • 链接取决于顺序。如果您的编译行,您是否尝试将-lpthread 放在末尾?
  • @FredLarson 这似乎是诀窍。我知道在某些情况下链接器顺序很重要,但是这个让我陷入了循环。显然,这是在 GCC 中实施更严格行为的实际努力的一部分。您可以添加一个我可以接受的答案吗?谢谢!
  • 实际上,我认为@Slava 给出了更好的答案。看到这个:stackoverflow.com/q/2127797/10077

标签: c++ linux gcc linker


【解决方案1】:

要在 gcc 中启用多线程,您应该传递 -pthread 标志而不是 -lpthread -

-pthread

       Add support for multithreading using the POSIX threads library.                
       This option sets flags for both
       the preprocessor and linker.  
       It does not affect the thread safety of object code produced by the
       compiler or that of libraries supplied with it.

【讨论】:

  • 为什么不直接链接库呢?这有什么理由吗?
  • @Mr.Shickadance 因为-pthreads 不仅链接库,还为预处理器设置标志,因此某些库头可能会以不同方式编译。
猜你喜欢
  • 2014-03-14
  • 1970-01-01
  • 2023-03-11
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
相关资源
最近更新 更多