CMake: Replace compile flags of an INTERFACE target

北城以北 提交于 2019-12-04 22:17:43

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

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!