14

In the root CMakeLists.txt I have

add_definition(-DMY_MACRO) 

Then in a sub CMakeLists.txt I want to do something like

add_library(mylib, STATIC file1 #ifdef MY_MACRO file2 #endif ) 

I tried something like

IF( DEFINED MY_MACRO ) SET(FILE2 "file2") ELSE( DEFINED MY_MACRO ) SET(FILE2 "") END_IF( DEFINED MY_MACRO ) add_library(mylib static file1 ${FILE2} ) 

but no joy.

2 Answers 2

12

add_definitions add a preprocessor definition, it does not define a cmake variable.

I have not tested, but if you really want to look for a preprocessor definition, maybe more something like this:

set(mylib_SOURCES ) list(APPEND mylib_SOURCES file1) get_directory_property(CURRENT_DEFINITIONS COMPILE_DEFINITIONS) list(FIND CURRENT_DEFINITIONS "MY_MACRO" IN_CURRENT_DEFINITIONS) if(NOT IN_CURRENT_DEFINITIONS EQUAL -1) list(APPEND mylib_SOURCES file2) endif(NOT IN_CURRENT_DEFINITIONS EQUAL -1) add_library(mylib static ${mylib_SOURCES}) 

(definitions are inherited from parent directories here)

And in your parent CMakeLists.txt:

add_definitions(-DMY_MACRO) # should appear before going into subdirectories add_subdirectory(foo) 

A different approach, based on a variable, would be:

  • parent:

    option(WITH_FOO "with(out) foo option") # or set(WITH_FOO true/false) if(WITH_FOO) add_definitions(-DMY_MACRO) endif(WITH_FOO) add_subdirectory(foo) 
  • subdirectory:

    set(mylib_SOURCES ) list(APPEND mylib_SOURCES file1) if(WITH_FOO) list(APPEND mylib_SOURCES file2) endif(WITH_FOO) add_library(mylib static ${mylib_SOURCES}) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you set me on the right track. I just set a cmake variable at the same place the macro is defined. Saves a lot of faff.
2

You can use also generator expression:

add_library(mylib, STATIC file1 $<$<BOOL:${SOME_VARIABLE}>:file2> ) 

1 Comment

This works, but if you try to access variable SOURCES later in cmake, it will have this ugly $<$<BOOL:ON>:file2> item in it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.