Linux下undefined reference to ‘pthread_create’問題解決
在試用Linux 線程模塊時,試用pthread_create 函數。
編譯命令為 gcc main.c -o test
時,會出現如下錯誤
/tmp/ccIvH3bU.o: In function `main':
main.c:(.text+0x81): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
問題的原因:pthread不是linux下的默認的庫,也就是在鏈接的時候,無法找到phread庫中哥函數的入口地址,於是鏈接會失敗。
解決:在gcc編譯的時候,附加要加 -lpthread參數即可解決。
試用如下命令即可編譯通過
gcc main.c -o test -lpthread
#include <unistd.h>
#include <pthread.h>
#define NUM 10
int count;
void* thread_func(void *arg)
{
count++;
printf("count %d\n", count);
return;
}
int main()
{
pthread_t tid[NUM];
int i = 0;
for (i = 0; i < NUM; i++)
{
pthread_create(&tid[i], NULL, thread_func, NULL);
}
sleep(1);
return 0;
}