简体   繁体   English

使用 G++ 强制链接到 pthread

[英]Force linking to pthread with G++

I am having some trouble with one of my projects.我的一个项目遇到了一些问题。 It seems that I link towards a library that requires pthread symbols, but the library itself is not linked with pthread.似乎我链接到需要 pthread 符号的库,但库本身未与 pthread 链接。 The symptoms is that the program segfaults when I try to run it.症状是程序在我尝试运行时出现段错误。 I ran:我跑了:

LD_DEBUG=all ./my_program

and found out it segfaults while looking for pthread_create.并在寻找 pthread_create 时发现了它的段错误。 The program runs if I force preload of pthread using this command:如果我使用以下命令强制预加载 pthread,程序将运行:

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

To solve this problem I thought I'd just link my_program with pthread in the build script using -lpthread.为了解决这个问题,我想我只需在构建脚本中使用 -lpthread 将 my_program 与 pthread 链接起来。 That didn't work so I tried -pthread.那没有用,所以我尝试了 -pthread。 Didn't work either.也没有用。 I was able to reproduce this to the bare minimal:我能够将其重现到最低限度:

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)

As you can see from the output of ldd, my_program is not linked with pthread.从 ldd 的输出中可以看出,my_program 没有与 pthread 链接。 I suspected that this happens because g++ understands I am not actually using any symbols from pthread and does not link with it.我怀疑发生这种情况是因为 g++ 知道我实际上没有使用 pthread 中的任何符号并且没有与之链接。 So I tried adding a call to pthread_create:所以我尝试添加对 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)

Please ignore the warnings, I know the call to pthread_create is bogus.请忽略警告,我知道对 pthread_create 的调用是伪造的。 The point is that now it actually links with pthread.关键是现在它实际上与 pthread 链接。

So my question is: Is there anyway to force g++ to link with something (in this case pthread) without adding dummy code using the symbols?所以我的问题是:无论如何要强制 g++ 链接到某些东西(在这种情况下是 pthread)而不使用符号添加虚拟代码?

Is there anyway to force g++ to link with something (in this case pthread) without adding dummy code using the symbols?无论如何要强制 g++ 链接到某些东西(在这种情况下是 pthread)而不使用符号添加虚拟代码?

Try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM