创建线程报错 undefined reference to `pthread_create'

创建线程

#include
#include
void* say_hello(void* args){
	printf("hello from thread\n");
	pthread_exit((void*)1);	
} 
int main(){
	pthread_t tid;
	int iret=pthread_create(&tid,NULL,say_hello,NULL);
	if(iret){
		printf("pthread_creat error:iret=%d\n",iret);
		return iret;
	}
	void *retval;
	iret=pthread_join(tid,&retval);
	if(iret)
	{
		printf("pthread_join error:iret=%d\n",iret);
		return iret;
	}
	printf("retval=%ld\n",(long)retval);
	return 0;
}

编译

g++ -lpthread -o test test.cpp

如果报错

/tmp/ccJ0xBgG.o: In function `main':
test.cpp:(.text+0x4e): undefined reference to `pthread_create'
test.cpp:(.text+0x83): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status

把-lpthread放到最后

g++ -o test test.cpp -lpthread

你可能感兴趣的:(c++)