当前位置: 技术问答>linux和unix
请教一个静态编译问题
来源: 互联网 发布时间:2016-11-18
本文导语: 一段代码,实现创建线程功能,文件名为thread.c。在终端中输入:gcc -lpthread -o thread_create thread_create.c,可以正确编译。但是在后面加上-static后(即gcc -lpthread -o thread_create thread_create.c -static)出现了问题。问题如下...
一段代码,实现创建线程功能,文件名为thread.c。在终端中输入:gcc -lpthread -o thread_create thread_create.c,可以正确编译。但是在后面加上-static后(即gcc -lpthread -o thread_create thread_create.c -static)出现了问题。问题如下:
/tmp/ccskh5cb.o: In function `thr_fn':
thread_create.c:(.text+0x8): undefined reference to `pthread_self'
/tmp/ccskh5cb.o: In function `main':
thread_create.c:(.text+0x58): undefined reference to `pthread_create'
thread_create.c:(.text+0x85): undefined reference to `pthread_self'
collect2: ld returned 1 exit status
请问这是什么原因导致的。该如何解决。
程序代码如下:
#include
#include
void *thr_fn(void *arg);
void *thr_fn(void *arg)
{
printf("new thread:pid is :%u tid is:%un",getpid(),pthread_self());
}
int main()
{
int err;
pthread_t tid;
while(1)
{
err=pthread_create(&tid,NULL,thr_fn,NULL);
if(err!=0)
printf("can't create thread:%sn",strerror(err));
printf("main thread:pid is :%u tid is:%un",getpid(),pthread_self());
sleep(5);
}
exit(0);
}
/tmp/ccskh5cb.o: In function `thr_fn':
thread_create.c:(.text+0x8): undefined reference to `pthread_self'
/tmp/ccskh5cb.o: In function `main':
thread_create.c:(.text+0x58): undefined reference to `pthread_create'
thread_create.c:(.text+0x85): undefined reference to `pthread_self'
collect2: ld returned 1 exit status
请问这是什么原因导致的。该如何解决。
程序代码如下:
#include
#include
void *thr_fn(void *arg);
void *thr_fn(void *arg)
{
printf("new thread:pid is :%u tid is:%un",getpid(),pthread_self());
}
int main()
{
int err;
pthread_t tid;
while(1)
{
err=pthread_create(&tid,NULL,thr_fn,NULL);
if(err!=0)
printf("can't create thread:%sn",strerror(err));
printf("main thread:pid is :%u tid is:%un",getpid(),pthread_self());
sleep(5);
}
exit(0);
}
|
这样呢?
gcc -o thread_create thread_create.c -lpthread -static
gcc -o thread_create thread_create.c -lpthread -static
|
注意链接库的顺序:
gcc -lpthread -o thread_create thread_create.c -static
改为:
gcc -static -o thread_create thread_create.c -lpthread
gcc -lpthread -o thread_create thread_create.c -static
改为:
gcc -static -o thread_create thread_create.c -lpthread