nVxx
nVxx

Reputation: 691

CMake: propagate compile options project-wide

Lets say I want to compile all the code with /W4 for a project with three libs/targets.

A -> B -> C

What is the best practice to apply the flag project-wide?

I can think of two approaches:

  1. Set TARGET_COMPILE_OPTIONS(C PUBLIC "\W4") in C's CMake (which is a core library for the whole project) and every other library that depends on C will inherit the flag via: TARGET_LINK_LIBRARIES(B C)
    Pro: new libraries will inherit the flag automatically.
    Con: compile flags for a project are implicit.

  2. Specify compile options for every target/lib separately.
    Pro: the flags are explicitly specified and manageable separately for each lib.
    Con: the flags need to be (not forgotten to be) set for a new lib.

Upvotes: 4

Views: 2450

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

Third option, change the compiler flags.

For instance, when I want to activate address sanitizer on the whole project, I do:

SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address -static-libasan")
SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address -static-libasan")

The current idiomatic way of setting flags for the current folder and subfolder is to use

add_compile_options(-fsanitize=address) 

Upvotes: 3

Related Questions