Andreas
Andreas

Reputation: 10067

Use local compiler flags in CMake

I have a CMakeLists.txt which imports several static libraries like so:

add_subdirectory("/foo/bar" "/bar/foo")
add_subdirectory("/foo2/bar" "/bar2/foo")

In my main CMakeLists.txt I set CMAKE_C_FLAGS like this:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ...my flags...")

All static libraries which I import using add_subdirectory seem to inherit these flags as well now but I don't want that! Is there any way to set the compiler flags locally, i.e. just for the source files inside the respective CMakeLists.txt file instead of the whole project?

Upvotes: 2

Views: 1442

Answers (2)

jiandingzhe
jiandingzhe

Reputation: 2121

Current versions of CMake suggests to use target-specific commands, such as target_include_directories, target_compile_options, target_compile_definitions. These commands only affect specified target (and possibly the target's descendant users).

Please refer to CMake-commands doc for more details.

Upvotes: 0

Tsyvarev
Tsyvarev

Reputation: 65928

Command add_compile_options sets compiler flags only for targets inside current CMakeLists.txt (and subdirectories):

CMakeLists.txt:

add_subdirectory("foo/bar" "/bar/foo")
add_executable(main_exe ...) # Unaffected by 'add_compile_options' below.

foo/bar/CMakeLists.txt:

# set flags for futher targets in current CMakeLists.txt
add_compile_options(<my_flags>)
add_executable(sub_exe ...) # Affected by 'add_compile_options' above.

Upvotes: 1

Related Questions