【问题标题】:Using CMakeLists.txt with multiple targets with different flags将 CMakeLists.txt 与具有不同标志的多个目标一起使用
【发布时间】:2020-09-06 13:39:10
【问题描述】:

我正在尝试使用 CMakeLists.txt 将以下文件编译成两个不同的可执行文件。

这个文件是:main.cpp

#include <iostream>
#include <cassert>

int main(int, char**) {
    std::cout << "Hello, world!\n";
    assert(0);
    return 0;
}

这是CMakeLists.txt 文件

cmake_minimum_required(VERSION 3.0.0)
project(multi_Tar VERSION 0.1.0)


SET(CMAKE_CXX_FLAGS "-O3 -DNDEBUG")
SET(CMAKE_CXX_FLAGS_RELEASE "-O0")
add_executable(multi_Tar main.cpp)

add_executable(tests main.cpp)
set_target_properties(tests PROPERTIES COMPILE_FLAGS "${CMAKE_CXX_FLAGS_RELEASE}")

此解决方案不起作用。当我运行 ./tests 时,我没有收到断言错误。


动机是使用相同的CMakeLists.txt 来测试有效性,并对相同的代码进行基准测试。


感谢您的帮助。

在@squareskittles 回答后编辑:

感谢您的回答!

(包括答案​​的代码:)

cmake_minimum_required(VERSION 3.0.0)
project(multi_Tar VERSION 0.1.0)

add_executable(multi_Tar main.cpp)
# Add the compile options for multi_Tar.
target_compile_definitions(multi_Tar PRIVATE -O3 -DNDEBUG)

add_executable(tests main.cpp)
# Add the compile options for tests.
target_compile_definitions(multi_Tar PRIVATE -O0)

我尝试使用您的解决方案,但出现以下错误:

<command-line>: error: macro names must be identifiers
<command-line>: error: macro names must be identifiers
CMakeFiles/multi_Tar.dir/build.make:62: recipe for target 'CMakeFiles/multi_Tar.dir/main.cpp.o' failed
make[2]: *** [CMakeFiles/multi_Tar.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/multi_Tar.dir/all' failed
make[1]: *** [CMakeFiles/multi_Tar.dir/all] Error 2
Makefile:105: recipe for target 'all' failed
make: *** [all] Error 2

我尝试稍微更改CMakeLists.txt,但没能成功。

此外,您的解决方案中的最后一行是否应该是:

target_compile_definitions(multi_Tar PRIVATE -O0)

target_compile_definitions(tests PRIVATE -O0)

【问题讨论】:

    标签: c++ visual-studio-code cmake


    【解决方案1】:

    根据 CMake 代码,tests 可执行文件应该产生断言错误。您添加了NDEBUG 编译定义,根据assert 文档禁用assert 宏。

    如果您想将编译标志应用到特定 CMake 目标,您应该使用目标特定的 CMake 命令,例如 target_compile_optionstarget_compile_definitions。我不确定您在哪里找到此 CMake 代码,但手动修改 CMAKE_CXX_FLAGS* 变量是不鼓励并且通常没有必要,尤其是在较新版本的 CMake 中。

    尝试这样的事情,将NDEBUG 标志only应用于multi_Tar 目标:

    cmake_minimum_required(VERSION 3.0.0)
    project(multi_Tar VERSION 0.1.0)
    
    add_executable(multi_Tar main.cpp)
    # Add the compile options for multi_Tar.
    target_compile_options(multi_Tar PRIVATE -O3 -DNDEBUG)
    
    add_executable(tests main.cpp)
    # Add the compile options for tests.
    target_compile_options(tests PRIVATE -O0)
    

    【讨论】:

    • 感谢您的回答:)。我无法编译它,不知道为什么。
    • @TheHolyJoker 查看更新的响应,是的,最后一行应该特定于 tests 目标。并修复了CMake代码,这里正确的命令应该是target_compile_options
    猜你喜欢
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2020-09-01
    相关资源
    最近更新 更多