Use CMake cache variables to enable/disable parts of the project. Don’t try to have incomplete information in the things that CMake sees and then try to avoid problems by just not building the incomplete targets.
A typical arrangement I would use for this sort of scenario might look something like this:
option(MYPROJ_ENABLE_SOMEFEATURE "Helpful doc string here" ON) # See below
if(MYPROJ_ENABLE_SOMEFEATURE)
add_subdirectory(somefeature_subdir)
endif()
In the above, I’ve explicitly specified the default value for the switch to be ON
. If I left that out, the default would be OFF
. In your project, you may want to do some logic before that to work out whether you want the default to be ON
or OFF
. For example, you may check if certain required dependencies are available.
The above also assumes your project is nicely structured such that this optional part of the project is self-contained in a subdirectory. It doesn’t have to be that way, but it is often clearer and easier to work with and maintain like that. If you need to keep things in the same directory, just put the feature-specific bits directly in the if()
block. Eg
option(MYPROJ_ENABLE_SOMEFEATURE "Helpful doc string here" ON) # See below
if(MYPROJ_ENABLE_SOMEFEATURE)
add_library(somefeature src1.cpp src2.cpp)
target_link_library(someotherthing PRIVATE somefeature)
# ... etc ...
endif()
Another variation is to choose between a set of implementations (kinda of like an enum
in C++). This would be suitable where exactly one choice from a limited set of choices has to be made.
set(MYPROJ_FEATUREIMPL SLOW_BUT_SAFE CACHE STRING "Helpful doc string here")
if(MYPROJ_FEATUREIMPL STREQUAL SLOW_BUT_SAFE)
# ... Do whatever
elseif(MYPROJ_FEATUREIMPL STREQUAL SCARY_FAST)
# ... Do whatever
else()
message(FATAL_ERROR "${MYPROJ_FEATUREIMPL} is not a supported implementation.")
endif()
You can add more niceties to the above, such as making CMake GUI aware of the supported choices so that it presents a combobox to the user instead of an arbitrary text entry field.