簡體   English   中英

CMake:替換INTERFACE目標的編譯標志

[英]CMake: Replace compile flags of an INTERFACE target

我需要更換/std:c++14標志的的INTERFACE目標(僅首標庫)與/std:c++17 CMake還不支持直接在VS中設置C ++ 17標志(請參閱如何使用CMake在VS2017中啟用/ std:c ++ 17 ),所以我需要手動替換它。

但是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

怎么辦呢?

對於接口庫,您需要更改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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM