问题
VScode在Ubuntu中执行多线程程序时,您的环境中可能会出现类似下面的报错提示:
in function `main':
hw2_2.cpp:(.text+0x4d): undefined reference to `pthread_create'
/usr/bin/ld: hw2_2.cpp:(.text+0x5e): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
在Ubuntu平台下调用pthread_create()
函数,用gcc
编译时出现Undefined reference to 'pthread_create'
的问题。是因为pthread
库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a
,所以在使用pthread_create()
创建线程,以及调用 pthread_join()
函数时,需要链接该库。
解决方案
方案一
每次编译的时候加上 -pthread
:
g++ project.cpp -o project -pthread
方案二
在VScode里使其链接到这个静态库,即修改tasks.json
文件,然后直接Ctrl/Command + F5编译运行。(注意是F5)
另外,一个建议是,网上很多人说建议尝试-lpthread
,这里建议使用:
gcc -pthread
而不是 -lpthread
,-lpthread
链接到libpthread
,-pthread
链接到 libpthread
和一堆其他东西。