欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > linux >内容正文

linux

Linux下undefined reference to ‘pthread_create’问题解决

发布时间:2025/6/15 linux 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Linux下undefined reference to ‘pthread_create’问题解决 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Linux下undefined reference to ‘pthread_create’问题解决

在试用Linux 线程模块时,试用pthread_create 函数。
编译命令为 gcc main.c -o test时,会出现如下错误

/usr/bin/ld: /tmp/ccAusWl8.o: in function `main': 05_concurrent_server_thread.c:(.text+0x44c): undefined reference to `pthread_create' /usr/bin/ld: 05_concurrent_server_thread.c:(.text+0x468): undefined reference to `pthread_detach' collect2: error: ld returned 1 exit status

  问题的原因:pthread不是linux下的默认的库,也就是在链接的时候,无法找到phread库中该函数的入口地址,于是链接会失败。

解决:在gcc编译的时候,附加要加 -lpthread参数即可解决。

试用如下命令即可编译通过

gcc main.c -o test -lpthread

如下编译通过 

#include<stdlib.h> #include<stdio.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<unistd.h> #include <signal.h> #include <sys/wait.h> #include <pthread.h>#define N 128void handler(int sig){wait(NULL); }typedef struct{struct sockaddr_in addr;int acceptfd; }MSG;void *pthread_fun(void *arg){int count = 0;ssize_t bytes;MSG msg = *(MSG *)arg; char buf[N] = "666";char text[N] = "";while(1){// 打印客户端信息printf("ip:%s, port:%d\n", inet_ntoa(msg.addr.sin_addr), ntohs(msg.addr.sin_port));// 接收数据if((count = recv(msg.acceptfd,text,N,0))==-1){perror("fail to recv");exit(1);}else if(count == 0){printf("The client quited\n");pthread_exit(NULL);}printf("from client: ");for(int j=0;j<count;j++){printf("%c",text[j]);}printf("\n");//发送buf数据if(send(msg.acceptfd,buf,sizeof(buf),0)==-1){perror("fail to send");exit(1);}} }int main(int argc, char const * argv[]){if(argc < 3){fprintf(stderr, "server Usage:%s ip port\n",argv[0]);exit(1);}int sockfd;// 创建tcp套接字if((sockfd=socket(AF_INET,SOCK_STREAM,0)) == -1){perror("fail to socket");exit(1);}struct sockaddr_in serveraddr;socklen_t addrlen = sizeof(serveraddr); serveraddr.sin_family = AF_INET; // 协议族 AF_INET:ipv4网络协议// inet_addr: 将点分十进制字符串ip地址转为整形数据serveraddr.sin_addr.s_addr = inet_addr(argv[1]); // ip地址// atoi 将数字型字符串转换为整形数据// htons 将主机字节序转化为网络字节序serveraddr.sin_port = htons(atoi(argv[2]));// 将套接字和网络信息绑定if(bind(sockfd,(struct sockaddr*)&serveraddr, addrlen) == -1){perror("fail to connect");exit(1);};// 将套接字设置为监听状态if(listen(sockfd,5) == -1){perror("fail to listen");exit(1);}struct sockaddr_in clientsock;addrlen = sizeof(clientsock);printf("准备阻塞...\n");// 使用信号,异步的方式处理僵尸进程signal(SIGCHLD,handler);while(1){ // 阻塞等待客户端的链接int clisock = accept(sockfd,(struct sockaddr*)&clientsock, &addrlen);// 创建子线程与客户端通信MSG msg;msg.addr = clientsock;msg.acceptfd = clisock;pthread_t thread;if(pthread_create(&thread,NULL,pthread_fun,&msg)!=0){perror("fail to pthread_create");}pthread_detach(thread);}// 关闭套接字描述符//close(clisock);//close(sockfd);return 0; }

 

总结

以上是生活随笔为你收集整理的Linux下undefined reference to ‘pthread_create’问题解决的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。