Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: propagate compile options project-wide

Tags:

c++

cmake

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.

like image 610
nVxx Avatar asked Nov 16 '25 13:11

nVxx


1 Answers

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) 
like image 194
Matthieu Brucher Avatar answered Nov 18 '25 06:11

Matthieu Brucher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!