cmake - Global linker flag setting (for all targets in directory)

前端 未结 1 1848
执笔经年
执笔经年 2020-12-02 00:43

I want to pass linker flags to all sub-projects (sub-directory CMakeList) in my project.

Before switching to new cmake 3.3, I was using the following code (cmake 3.2

相关标签:
1条回答
  • 2020-12-02 01:30

    Your problems are/were not related to a specific CMake version.

    It's the same for all linker/compiler flag variables in CMake. Because those variables are cached variables and set with the project()/enable_language() command (details see here), you either have to

    1. prefill the cache with set(... CACHE ...) before the project() command
    2. generally use the set(... CACHE ... FORCE) to force/overwrite
    3. move the set() after the project() command to hide or append to the cached variables

    Here is an example for CMAKE_EXE_LINKER_FLAGS showing all three variants:

    CMakeLists.txt

    cmake_minimum_required(VERSION 2.8)
    
    # 1. prefill
    #set(CMAKE_EXE_LINKER_FLAGS "-Wl,-Map=output.map" CACHE INTERNAL "")
    
    project(Test_Project CXX)
    
    # 2. force
    set(CMAKE_EXE_LINKER_FLAGS "-Wl,-Map=output.map" CACHE INTERNAL "" FORCE)
    
    # 3. hide
    #set(CMAKE_EXE_LINKER_FLAGS "-Wl,-Map=output.map")
    # 3. or append
    #set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Map=output.map")
    
    # TODO: Remove, this is just for testing
    file(WRITE "foo.cpp" "int main() {}") 
    
    add_executable(${PROJECT_NAME} foo.cpp)
    

    Whatever the values of those variables are at the end of your any given CMakeLists.txt file will be applied to all corresponding targets in the same CMakeLists.txt file as defaults (see CMAKE - setting compile flags for libraries and What's the CMake syntax to set and use variables?).

    The first variant has the disadvantage that it's really only the initial value. The second and third variant would most likely need an if (CMAKE_COMPILER_IS_GNUCXX) around it, so I prefer the second variant with moving those settings to its own initial-cache file:

    MyGNUSettings.cmake

    set(CMAKE_CXX_FLAGS "-stdlib=libstdc++ -Wfatal-errors" CACHE INTERNAL "" FORCE)
    set(CMAKE_CXX_FLAGS_DEBUG "-g" CACHE INTERNAL "" FORCE)
    set(CMAKE_CXX_FLAGS_RELEASE "-O3" CACHE INTERNAL "" FORCE)
    set(CMAKE_EXE_LINKER_FLAGS "-Wl,-Map=output.map" CACHE INTERNAL "" FORCE)
    

    Using e.g.

    cmake -G "Unix Makefiles" -C MyGNUSettings.cmake -DCMAKE_BUILD_TYPE=Release  .
    

    And yes - for the global and per compiler settings - I prefer the global cached variables over the add_compile_options() command. I think add_compile_options() haven't replaced the global variables, it was mainly introduced to prevent people putting compiler options in add_definitions() commands.

    0 讨论(0)
提交回复
热议问题