Linux多线程编程g++编译出错,解决pthread_create未定义引用问题

网安智编 厦门萤点网络科技 2026-02-14 00:12 35 0
转载:  参考:  参考:  在学习Linux下面的多线程编程时,照着书上敲了一段代码,但是使用g++编译时却出现问题。 #include #include #include #include #include /...

转载: 

参考: 

参考: 

在学习Linux下面的多线程编程时,照着书上敲了一段代码,但是使用g++编译时却出现问题。

#include   
#include   
#include   
#include   
#include  //此处需要加
using namespace std;  
  
void printids(const char* s)  
{  
        pid_t pid;  
        pthread_t tid;  
  
        pid = getpid();  
        tid = pthread_self();  
  
        printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);  
  
}  
  
void* thr_fn(void *args)  
{  
        printids("new thread: ");  
        return ((void*)0);  
}  
  
int  main()  
{  
        pthread_t ntid;  
        int err;  
        err = pthread_create(&ntid, NULL, thr_fn, NULL);  
        if( err != 0 )  
        {  
                printf("can't create thread: %d\n", err);  
                exit(1);  
        }  
        printids("main thread:");  
        sleep(1);  
        return 0;  
}  

使用g++ main.cpp -o main编译出现下面问题:

/tmp/.o: In `main':

pthread.h头文件下载_pthread库静态库libpthread.a_g++编译pthread_create未定义引用

main.cpp:(.text+0xce): to `'

: ld 1 exit

查找资料知道, 库不是 Linux 系统默认的库,连接时需要使用静态库 .a,所以在使用()创建线程时,在编译中要加 -参数。

使用g++ main.cpp -o main -将线程库包含后编译即可运行。