CMake:替换INTERFACE目标的编译标志 [英] CMake: Replace compile flags of an INTERFACE target

查看:295
本文介绍了CMake:替换INTERFACE目标的编译标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to replace the /std:c++14 flag of an INTERFACE target (header-only library) with /std:c++17. CMake doesn't support setting C++17 flags in VS directly yet (see How to enable /std:c++17 in VS2017 with CMake) so I need to manually replace it.

但是 get_target_property(my_compile_flags mylib COMPILE_OPTIONS)可以检索当前设置的标志列表,然后替换/ std:具有/ std:c ++ 17的c ++ 14无法正常工作:

However get_target_property(my_compile_flags mylib COMPILE_OPTIONS) to retrieve the list of currently set flags to then subsequently replace /std:c++14 with /std:c++17 doesn't work:


INTERFACE_LIBRARY目标只能具有列入白名单的属性。

INTERFACE_LIBRARY targets may only have whitelisted properties. The property "COMPILE_OPTIONS" is not allowed.

不过,您可以通过 target_compile_features(...)进行设置。 并通过例如 target_compile_options(mylib界面/ std:c ++ 17)。但是后一个命令添加标志,而不删除 / std:c ++ 14

You can set them however via target_compile_features(...) and manually via e.g. target_compile_options(mylib INTERFACE /std:c++17). But the latter command adds the flag, without removing /std:c++14.

该怎么做?

推荐答案

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

For an interface library you need to change INTERFACE_COMPILE_DEFINITIONS instead of COMPILE_DEFINITIONS (see add_library(INTERFACE)).

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

Here is a full example I've tested with VS2017 (using /std:c++latest since not yet supported /std:c++17 may be ignored/removed by 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)

这篇关于CMake:替换INTERFACE目标的编译标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆