【问题标题】:Using CMakeLists causes error while compiling fine in commandline在命令行中编译文件时使用 CMakeLists 会导致错误
【发布时间】:2017-06-22 23:20:24
【问题描述】:

我正在编译我的代码,其中我在 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

它编译没有任何问题。

这可能是什么问题/解决方案?

【问题讨论】:

标签: gcc cmake posix clion


【解决方案1】:

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

add_executable()之后添加:

target_link_libraries(Test pthread)

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2010-12-02
    相关资源
    最近更新 更多