cmake

How to change compilation flags for a folder with CMake?


I'm generating Makefiles for my project using CMake.

I would like to compiler some files with different options. For instance, all the files with -fX, but the files in test folder with -fno-X.

Is that possible in CMake ?

Here is the part of my CMakeLists.txt file with the source files:

file(
    GLOB_RECURSE
    compiler_files
    src/*.cpp
)

file(GLOB to_remove src/eddi.cpp)
list(REMOVE_ITEM compiler_files ${to_remove})

add_library(Compiler OBJECT ${compiler_files})

add_executable(eddic $<TARGET_OBJECTS:Compiler> src/eddi.cpp)
target_link_libraries (eddic boost_program_options)

Solution

  • You can add compilation flags to specific files with the set_source_files_properties command:

    SET_SOURCE_FILES_PROPERTIES(
      ${list_of_noX_files}
      PROPERTIES
      COMPILE_FLAGS "-fno-X"
    )
    

    In this case the files listed in the variable list_of_noX_files will be compiled with the option -fno-X appended to the default options.