Ender
Ender

Reputation: 1778

How to not compile parts of CMakeLists.txt using cmd line parameters?

I'm using CMake 3.10.2 and have this in place in one of my target CMakeLists.txt files....

target_compile_definitions(mytarget PUBLIC USE_MY=${USE_MY})

I can then make use of parameters on the command line such as -DUSE_MY=0 so that I can put stuff like this in my c++ files:

#ifdef USE_MY
   // code left out
#endif

However, I'd also like to be able to leave out files in CMakeLists.txt from compiling.

set(my_sources
    filea.cpp
    fileb.cpp
    filec.cpp (how would I leave out filec.cpp?)
)

And in my top level CMakeLists.txt, leave out an entire library.

add_subdirectory(my_stuff/liba)
add_subdirectory(my_stuff/libb) (how to leave out this lib?)
add_subdirectory(my_stuff/libc

So I'd like to leave out certain files and targets from compiling as well. Thanks for any help on this.

Upvotes: 2

Views: 66

Answers (2)

Kevin
Kevin

Reputation: 18243

As @drescherjm suggested, something like this might work for you:

set(my_sources
    filea.cpp
    fileb.cpp
)
if(USE_MY)
    # Append filec if USE_MY is defined.
    set(my_sources ${my_sources} filec.cpp)
endif()

Similarly,

add_subdirectory(my_stuff/liba)
if(USE_MY)
    add_subdirectory(my_stuff/libb)
endif()
add_subdirectory(my_stuff/libc

# ... other code here ...

# Link the libraries.
target_link_libraries(targetA ${my_liba} ${my_libc})
if(USE_MY)
    target_link_libraries(targetA ${my_libb})
endif()

Upvotes: 2

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

In modern CMake you'd do something like this:

add_subdirectory(my_stuff/liba)

if (USE_MY)
    add_subdirectory(my_stuff/libb)
endif()

add_subdirectory(my_stuff/libc

Then for sources:

add_library(libB source1.cpp source2.cpp source3.cpp)

if (USE_MY)
    target_sources(libB source4.cpp source5.cpp)
endif()

Upvotes: 2

Related Questions