codeblocks 多线程编程时出现:对pthread_create未定义的引用,解决方法

解决pthread_create未定义引用
本文介绍了解决在使用pthread_create函数时遇到未定义引用错误的方法。通过在编译命令中添加-lpthread参数或者在CodeBlocks环境中正确配置链接库路径和选项,可以成功创建线程。

程序已经添加了#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);
}

运行结果:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值