Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally include a source file

Tags:

cmake

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.

like image 994
James Avatar asked Mar 13 '14 11:03

James


1 Answers

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})
    
like image 51
julp Avatar answered Oct 30 '22 14:10

julp