问题描述
- 选了一计算机系统的课,课程要求在 linux 系统上运行一些 C 的代码,学到多线程的地方,在 linux 上安装了一个集成开发环境:Jetbrain 公司的 Clion,但是编译线程程序的时候无论如何也无法编译成功,报的错误:
[2/2] Linking C executable untitled1
FAILED: untitled1
: && /usr/bin/cc -g CMakeFiles/untitled1.dir/main.c.o CMakeFiles/untitled1.dir/test2.c.o -o untitled1 && :
CMakeFiles/untitled1.dir/test2.c.o: In functionmain': /tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:21: undefined reference to
pthread_create’
/tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:25: undefined reference topthread_create' /tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:29: undefined reference to
pthread_join’
/tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:33: undefined reference to `pthread_join’
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
问题原因
- 因为通过编译器没有链接到线程库。所以我们通过下列的两种方法来进行手动链接:
问题解决方案1
- 使用命令行来显式地链接线程库
-l pthread
或者-pthread
来编译文件:
gcc test2.c -o test2 -lpthread
- 运行文件:
./test2 //注意这里没有扩展名
- 如果想编译运行一条龙,使用下面命令:
gcc test2.c -o test2 -lpthread && ./test2
方案2:修改 Clion 中的 CmakeLists.txt 文件
- 在 cmakelists.txt 文件末尾加这两行,
- 一定要注意,target_link_library 中要指定自己的工程名称哦!
find_package(Threads REQUIRED)
target_link_libraries(untitled Threads::Threads)
- 改完名称之后,需要将 cmakelists.txt 文件重新
reload
一下,reload 的按钮在 cmakelists.txt 页面的右上方。
一个粗心的提醒:
别忘了把其他文件里有主函数 main 的代码注释掉哦~否则会报下面的错误: