Cmake add_compile_definitions but for all targets

Viewed 1069

Is there a way to create definitions in cmake for all targets created. So far when I

add_compile_definitions(MYDEFINITION)

in my root CmakeLists.txt then it seems to only create those definitions for targets created in that file. But I want to create the definitions to all targets created in subdirectories. What is the best way to do this?

1 Answers

My usual solution to set properties for all target is simply to add a common target, that has interface properties I want to add to all targets.

add_library(common INTERFACE)

target_compile_definition(common INTERFACE MYDEFINITION)

The neat thing is you can also put other things like warning settings:

target_compile_options(common INTERFACE
    $<$<CXX_COMPILER_ID:MSVC>:/Wall>
    $<$<CXX_COMPILER_ID:GNU,Clang>:-Wall -Wextra>
)

After setting up common things in the common target, you can use it where necessary:

add_library(mylib ...)
add_executable(myexe ...)

target_link_libraries(mylib PRIVATE common)
target_link_libraries(myexe PRIVATE common)
Related