Linux下undefined reference to ‘pthread_create’問題解決


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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM