因為明天要學Linux 多線程所以就先預習了一下。
看著參考資料寫完建立線程函數時,進行編譯,擦,報告undefined reference to 'pthread_create'錯誤
我也引入了需要的標頭檔。
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void printfids(const char *s)
{
pid_t pid;
pthread_t tid;
pid=getpid();
tid=pthread_self();
printf("%s pid %u tid %u %u (0x%x) \n ",s,(unsigned int ) pid,
(unsigned int )tid,( unsigned int )pid);
}
void *thfun(void *arg)
{
printfids("new thread :");
return ((void *)0);
}
int main(int argc ,char *argv[])
{
int ret;
pthread_t pthid;
ret=pthread_create(&pthid,NULL,thfun,NULL);
//If attr is NULL, the default attributes shall be used.
//第二個參數if是NULL,則建立預設屬性的進程。
if(ret!=0)
perror("can't creat thread ");
printfids("main thread :");
sleep(1);
exit(0);
}
工gcc 編譯結果報告undefined reference to 'pthread_create'錯誤
左看看右看看,沒有錯啊,搞了半個小時沒有出來,於是就百了一下。
問題原因:
pthread 庫不是 Linux
系統預設的庫,串連時需要使用靜態庫 libpthread.a,所以在使用pthread_create()建立線程,需要連結該庫。
在編譯中要加 -lpthread參數
gcc thread.c -o thread -lpthread
thread.c為你寫的源檔案,不要忘了加上標頭檔#include<pthread.h>