【问题标题】:CMake: Replace compile flags of an INTERFACE targetCMake:替换 INTERFACE 目标的编译标志
【发布时间】:2017-07-07 18:54:20
【问题描述】:

我需要用/std:c++17 替换INTERFACE 目标(仅标头库)的/std:c++14 标志。 CMake 还不支持直接在 VS 中设置 C++17 标志(请参阅How to enable /std:c++17 in VS2017 with CMake),因此我需要手动替换它。

但是 get_target_property(my_compile_flags mylib COMPILE_OPTIONS) 检索当前设置的标志列表然后随后将 /std:c++14 替换为 /std:c++17 不起作用:

INTERFACE_LIBRARY 目标可能只有列入白名单的属性。不允许使用“COMPILE_OPTIONS”属性。

您可以通过target_compile_features(...) 设置它们,也可以通过例如手动设置它们。 target_compile_options(mylib INTERFACE /std:c++17)。但是后一个命令添加标志,而不删除/std:c++14

怎么办?

【问题讨论】:

    标签: c++ cmake c++17


    【解决方案1】:

    对于接口库,您需要更改INTERFACE_COMPILE_DEFINITIONS 而不是COMPILE_DEFINITIONS(请参阅add_library(INTERFACE))。

    这是我用 VS2017 测试过的完整示例(使用 /std:c++latest,因为尚不支持 /std:c++17 可能会被 CMake 忽略/删除):

    cmake_minimum_required(VERSION 3.8)
    
    project(InterfaceLibCppStd)
    
    include(CheckCXXCompilerFlag)
    
    file(WRITE "mylib/Definitions.h" [=[ 
        #define HELLO_TEXT "Hello Interface Lib"
    ]=])
    add_library(mylib INTERFACE)
    
    target_include_directories(mylib INTERFACE "mylib")
    target_compile_options(mylib INTERFACE "/std:c++14")
    
    file(WRITE "main.cpp" [=[
        #include "Definitions.h"
        #include <iostream>
    
        int main()
        {
            std::cout << HELLO_TEXT << std::endl;
        }
    ]=])
    add_executable(myexe "main.cpp")
    
    if (MSVC_VERSION GREATER_EQUAL "1900")
        CHECK_CXX_COMPILER_FLAG("/std:c++latest" _cpp_latest_flag_supported)
        if (_cpp_latest_flag_supported)
            get_target_property(_opt_old mylib INTERFACE_COMPILE_OPTIONS)
            string(REPLACE "14" "latest" _opt_new "${_opt_old}")
            set_target_properties(mylib PROPERTIES INTERFACE_COMPILE_OPTIONS "${_opt_new}")
       endif()
    endif()
    
    target_link_libraries(myexe PUBLIC mylib)
    

    【讨论】:

    • @Ela782 谢谢 :-) 不客气。只是很好 - 在回答时帮助我们/我 - 如果您可以请在未来的问题中添加 minimal reproducible example 作为测试用例。
    猜你喜欢
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多