ubuntu 12.10 多线程编译的问题

软件和网站开发以及相关技术探讨
回复
happyj2me
帖子: 7
注册时间: 2007-07-27 11:07

ubuntu 12.10 多线程编译的问题

#1

帖子 happyj2me » 2013-02-20 11:32

happyboy@happyboy-hp:~/workspace/c/apue/thread$ gcc -o printid -L/usr/lib/x86_64-linux-gnu/ -lpthread printid.c
/tmp/ccpZr1ny.o:在函数‘print_id’中:
printid.c:(.text+0x15):对‘pthread_self’未定义的引用
/tmp/ccpZr1ny.o:在函数‘main’中:
printid.c:(.text+0x81):对‘pthread_create’未定义的引用
collect2: 错误: ld 返回 1

对应的动态库文件是存在,为何还编译还报错呢?
happyboy@happyboy-hp:~/workspace/c/apue/thread$ ls -l /usr/lib/x86_64-linux-gnu/libpthread
libpthread.a libpthread_nonshared.a libpthread.so

看了下libpthread.so 其内容如下:
/* GNU ld script
Use the shared library, but some functions are only in
the static library, so try that secondarily. */
OUTPUT_FORMAT(elf64-x86-64)
GROUP ( /lib/x86_64-linux-gnu/libpthread.so.0 /usr/lib/x86_64-linux-gnu/libpthread_nonshared.a )
happyj2me
帖子: 7
注册时间: 2007-07-27 11:07

Re: ubuntu 12.10 多线程编译的问题

#2

帖子 happyj2me » 2013-02-20 12:41

搞明白了,把-lpthread 放到最后就可以了:
gcc -o printid printid.c -lpthread
头像
tangboyun
帖子: 701
注册时间: 2009-07-25 1:57
联系:

Re: ubuntu 12.10 多线程编译的问题

#3

帖子 tangboyun » 2013-02-20 13:40

你的原始问题出在链接选项位于obj文件前,应该是后。
其次,应该尽量使用-pthread而非-lpthread。读下手册吧,用-lpthread是有潜在问题的,gcc手册明确指出过链接pthread应该用-pthread选项(无需再加-lpthread)。用后者有附加的宏定义,可以保证libc链接的时候选择正确的库。
http://stackoverflow.com/questions/2127 ... -compiling
https://github.com/tangboyun
http://tangboyun.is-programmer.com/
提问的智慧————Eric Steven Raymond
回答的智慧————Andrew Clarke
吾尝终日而思矣,不如须臾之所学也;吾尝跂而望矣,不如登高之博见也。
急急急标题什么的,最讨厌了!
急急复急急,急急何其多,我生待急急,万事急急急。
回复