Search code examples
cmakecmakelists-options

Add variables defined in a list to add_compile_definitions() using cmake


I have a list of vars definedinside a cmake which is called using from main CMakeLists.txt:

add_custom_target(gen_a
   COMMAND ${CMAKE_COMMAND} -P "gen_sigs.cmake"
)
add_dependencies(${PROJECT_NAME} gen_a)

My gen_sigs.cmake:

set(SIG_LIST SIGNAL_A=0 SIGNAL_B=1 SIGNAL_C=0 )

I want to use this list to add preprocessor definitions to the compiler command line like (in main CMakeLists.txt):

add_compile_definitions( 
  SIGNAL_A=0 
  SIGNAL_B=1
  SIGNAL_C=0
)

I tried using the following but it does not work (in main CMakeLists.txt):

add_compile_definitions( 
  ${SIG_LIST}
)

I am new to cmake so any suggestions on how to make this work will be helpful. Also the add_custom_target is defined before the add_compile_definitions() still it doesn't help. My guess is there is some problem with the order of execution because the ${SIG_LIST} has no value when I am printing it in cmakelists.txt. Is there a way to add dependency to add_compile_definitions so that my add_custom_target command gets forcibly executed before the add_compiler_definitions()?


Solution

  • Your question is not very clear, but from what you've shown, the following should work:

    include("${CMAKE_CURRENT_SOURCE_DIR}/gen_sigs.cmake")
    
    target_compile_definitions(main_target PRIVATE ${SIG_LIST})
    

    Adding a custom target defers processing until build time, but what you (appear to) want to do is fundamentally a configure/generation time thing. include() will cause the external script to be executed in the same scope as the call, immediately.