异想天开

What's the true meaning of light, Could you tell me why

gcc备忘问题

日期:2014-07-01 18:12:43
  
最后更新日期:2014-07-01 22:49:06
【技术文章,非码农误入】
链接libtcmalloc_minimal.a静态库时,编译不错,提示"undefined reference to `pthread_atfork'"。 环境:
[code lang="cpp"]
[root@localhost data]# uname -a
Linux localhost.localdomain 2.6.32-431.1.2.0.1.el6.x86_64 #1 SMP Fri Dec 13 13:06:13 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
[root@localhost data]# gcc -v
使用内建 specs。
目标:x86_64-redhat-linux
配置为:../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
线程模型:posix
gcc 版本 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
[/code]
改为动态链接没错,记得之前也是出错过,mysql静态链接库时,失败。当时,还可能是版本与系统的问题,而这个静态库,是在机器新编译的。求助万能的搜索引擎:
网友olenb:
“Try just "-pthread", not "-lpthread", on the compiler flags”
网友Ibbo:
“Once upon a time not that long ago it was -lpthread.
But then gcc and g++ were updated (i know not from which version).
The good news here is that its only a makefile change unlike g++ changing to std some years back where you needed to edit your source fiiles to use iostream and not iostream.h along with using std;
So no your not a retard the geeks in the cellar are just messing with your head. Its their way of showing humour.
Ibbo”
我改为-pthread果然可以了。不过,趁着昨天,知道了gcc的specs作用。查看gcc的内建specs:
[code lang="cpp"]
*lib:
%{pthread:-lpthread}
[/code]
可以看出当参数为pthread时,还是会被替换为-lpthread。决定继续深入一步,打开gcc -v重新链接。发现了一个表面问题,与库连接的顺序有关,改为pthread巧合使顺序正确了(注意是巧合)。-lrt -lpthread参数在静态库libtcmalloc_minimal.a的前面,快速构建一个原型测试依赖:
[code lang="cpp"]
[root@localhost test]# cat b1.c
#include<stdio.h>
int foo()
{
printf(" foo function\n");
return 0;
}
[root@localhost test]# cat b2.c
#include<stdio.h>
extern int foo();
int bar()
{
printf(" -- bar -- \n");
foo();
return 0;
}
[root@localhost test]# cat b3.c
#include<stdio.h>
extern int foo();
extern int bar();
int main()
{
printf(" -- main --\n");
bar();
foo();
return 0;
}
[/code]
三种方式编译:
[code lang="cpp"]
[root@localhost test]# gcc -c b3.c -o b3.o
[root@localhost test]# gcc -c b2.c -o b2.o
[root@localhost test]# gcc -c b1.c -o b1.o
[root@localhost test]# gcc b1.o b2.o b3.o -o bout
[root@localhost test]# gcc b2.o b3.o b1.o -o bout1
[root@localhost test]# gcc b3.o b2.o b1.o -o bout2
[/code]
三种方式都通过编译,并运行正确。而依赖关系为b2.o依赖b1.o,b3.o依赖b2.o和b1.o。没有再继续下去验证了,暂作备忘。
参考1:
1.http://forums.fedoraforum.org/showthread.php?t=166795