CMake per file optimizations

后端 未结 1 1532
忘掉有多难
忘掉有多难 2021-01-14 07:42

Elsewhere the question has been asked, \"How do I turn off optimizations on one file?\" The answer is usually something like this:

cmake_minimum_required( VE         


        
1条回答
  •  礼貌的吻别
    2021-01-14 08:03

    You can't overwrite compiler options with the makefile CMake generators on source file level. Options are always appended (see my answer at Is Cmake set variable recursive? for the complete formula).

    This is - as far as I know - only supported with the Visual Studio solution/project generators. These generators have flag tables to identify flags that are in the same group/that does overwrite a previous defined flag.

    So yours is more like a feature request to also add compiler option tables to CMake's makefile generators.


    Alternatives

    I just wanted to add some crazy CMake magic I came up with as a workaround. Add the following to your main CMakeLists.txt after the project() command:

    if (CMAKE_BUILD_TYPE)
        define_property(
            SOURCE
            PROPERTY COMPILE_FLAGS 
            INHERITED 
            BRIEF_DOCS "brief-doc"
            FULL_DOCS  "full-doc"
        )
        string(TOUPPER ${CMAKE_BUILD_TYPE} _build_type)
        set_directory_properties(PROPERTIES COMPILE_FLAGS "${CMAKE_CXX_FLAGS_${_build_type}}")
        set(CMAKE_CXX_FLAGS_${_build_type} "")
    endif()    
    

    This example moves the CMAKE_CXX_FLAGS_ content into an new COMPILE_FLAGS directory property that is then linked to COMPILE_FLAGS source file property via define_property(... INHERITED ...).

    Now the build type specific flags are only defined in COMPILE_FLAGS for each source file and you can overwrite/change them e.g. with the code snippet from your example:

    set_source_files_properties( 
        hello.c 
        PROPERTIES
        COMPILE_FLAGS -O0 
    )
    

    References

    • Directory properties and subdirectories
    • CMake: How do I change properties on subdirectory project targets?

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