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})