在命令行中编译文件时使用 CMakeLists 会导致错误

Using CMakeLists causes error while compiling fine in commandline

我正在编译我的代码,其中我在 C 中使用 posix 个线程。

我正在使用 CLion 及其 CMakeLists.txt:

cmake_minimum_required(VERSION 3.7)
project(Test)

set(CMAKE_C_STANDARD 99)
add_definitions(-lpthread)

set(SOURCE_FILES main.c)

add_executable(Test ${SOURCE_FILES})

我遇到错误(例如:undefined reference tosem_init'`)。

建议的解决方案是添加 -lpthread 编译器标志,但我已经添加了它。

我从命令行编译了相同的代码:

gcc main.c -lpthread

编译没有问题

这有什么可能 problem/solution?

完全删除 add_definitions(-lpthread),因为 pthread 不是一个定义,而是一个库依赖项。

add_executable()之后添加:

target_link_libraries(Test pthread)

此外,如果您想查看 CMake 正在使用哪些命令而无需检查其文件,您可以在命令行中使用 cmake -DCMAKE_VERBOSE_MAKEFILE=ON ...

顺便说一句,总是喜欢所有 target_* 命令,例如 target_compile_definitions() 而不是旧式 add_definitions()。这使您的项目属性和依赖关系保持干净,并最大限度地减少不同目标之间的干扰。

如果经过上述修改后你的代码仍然编译不通过,那么很可能是代码本身错误(与CMake无关)。