How to set different compiler options for different sets of source files?

For a C++ project, for a single library and CMakeLists.txt file, I would like to set compiler options differently for sets of files. For example, I might want to enable warning -Wunused-parameter for some files but not others.

What is the correct pattern for doing this please?

set_property(SOURCE file1.cxx dir/file2.cxx … APPEND
  PROPERTY COMPILE_OPTIONS -Wunused-parameter)
1 Like

@ben.boeckel May I follow-up on my question and your answer please?

I’m currently using this pattern:

set (_lib_name "a_lib")

if(NOT MSVC)
    add_library(${_lib_name} OBJECT "")
    target_compile_options(${_lib_name} PRIVATE -Wunused-parameter)
endif()

target_sources(${_lib_name}
    PRIVATE
        fileA.cpp
        fileB.cpp
        fileC.cpp
        etc.
)

But I don’t want to apply -Wunused-parameter to fileC.cpp. So should I use something like the following?

set (_lib_name "a_lib")

if(NOT MSVC)
    add_library(${_lib_name} OBJECT "")
endif()

set(SRC_FILES
         fileA.cpp
         fileB.cpp
         etc.
)

target_sources(${_lib_name} PRIVATE ${SRC_FILES} fileC.cpp)

if(NOT MSVC)
    set_source_files_properties(${SRC_FILES} PROPERTIES COMPILE_OPTIONS "-Wunused-parameter")

    set_source_files_properties(fileC.cpp PROPERTIES COMPILE_OPTIONS "-fpermissive")
endif()

That seems OK because the second call will overwrite the first one’s settings for fileC.cpp. A comment may be in order.