c++ - 使用 G++ 强制链接到 pthread

标签 c++ linux linker g++ pthreads

我的一个项目遇到了一些问题。我似乎链接到一个需要 pthread 符号的库,但该库本身未与 pthread 链接。症状是当我尝试运行该程序时出现段错误。我跑了:

LD_DEBUG=all ./my_program

并在查找 pthread_create 时发现它出现段错误。如果我使用以下命令强制预加载 pthread,程序就会运行:

LD_PRELOAD=/lib/x86_64-linux-gnu/libpthread.so.0 ./my_program

为了解决这个问题,我想我只需使用 -lpthread 将 my_program 与构建脚本中的 pthread 链接起来。那不起作用,所以我尝试了-pthread。也没起作用。我能够以最低限度地重现这一点:

echo "int main() { return 0; }" | g++ -x c++ - -pthread -lpthread -o my_program && ldd my_program
linux-vdso.so.1 =>  (0x00007ffe4fd08000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f150ca5c000)
/lib64/ld-linux-x86-64.so.2 (0x000055ac8c275000)

从 ldd 的输出中可以看到,my_program 没有与 pthread 链接。我怀疑发生这种情况是因为 g++ 知道我实际上没有使用 pthread 中的任何符号,并且没有与其链接。所以我尝试添加对 pthread_create 的调用:

echo -e "#include <pthread.h>\n int main() { pthread_create(0,0,0,0); return 0; }" | g++ -x c++ - -pthread -o my_program && ldd my_program
<stdin>: In function ‘int main()’:
<stdin>:2:37: warning: null argument where non-null required (argument 1) [-Wnonnull]
<stdin>:2:37: warning: null argument where non-null required (argument 3) [-Wnonnull]
linux-vdso.so.1 =>  (0x00007ffd977f9000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fafe1bb6000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fafe17f1000)
/lib64/ld-linux-x86-64.so.2 (0x0000563ee0002000)

请忽略警告,我知道对 pthread_create 的调用是伪造的。关键是现在它实际上与 pthread 链接了。

所以我的问题是:有没有办法强制 g++ 与某些东西(在本例中为 pthread)链接,而不使用符号添加虚拟代码?

最佳答案

Is there anyway to force g++ to link with something (in this case pthread) without adding dummy code using the symbols?

试试这个:

echo "int main() { return 0; }" |
g++ -x c++ - -o my_program -Wl,--no-as-needed -lpthread -Wl,--as-needed

关于c++ - 使用 G++ 强制链接到 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37556673/

相关文章:

java - Linux 和 java : File is being created but text is not written

linux - wxWidgets 链接问题

c++ - 目标文件 "Version References"来自哪里?

c++ - cvScalar 的顺序

c++ - 如果我在 Windows 中编写深度数据包检测程序,我会错过什么重要的事情?

C++ 二维数组用文件中的最后一个元素值填充所有元素

c++ - 为什么我的程序同时进入 if 语句和相应的 else 语句?

在 Linux 系统中更改日期,但重启后新日期丢失

linux - Linux下的程序员编辑器探秘

c++ - 如何阅读 MSVC C++ 链接错误