程序已经添加了#include<pthread.h>头文件,但编译却提示:
对‘pthread_create’未定义的引用
由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
gcc pthread.c -lpthread -o pthread
下面是codeblocks的修改:
设置>>编译器设置>>全局编译器设置>>链接器设置:
左侧链接库加入: /usr/lib64/libpthread.a
右侧其他链接器选项加入: -lpthread
如果你的libpthread.a不在lib64下可以用如下命令查找:
$ locate libpthread.a
测试程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_t tid;
void *thrd_func(void *arg)
{
printf("New process: PID: %d, TID: %lu\n", getpid(), pthread_self());
printf("New process: PID: %d, TID: %lu\n", getpid(), tid);
pthread_exit(0);
}
int main()
{
if (pthread_create(&tid, 0, thrd_func, 0)) {
printf("Create thread error!\n");
exit(1);
}
printf("TID in pthread_create function: %lu\n", tid);
printf("Main process: PID: %d, TID: %lu\n", getpid(), pthread_self());
sleep(1);
}
运行结果: