Home > OS >  Add option to CLI based on CMake configuration
Add option to CLI based on CMake configuration

Time:10-20

I have written a program prg which can be run using bash with some subcommands like so

$ prg subcommand1
Output of subcomman1
$ prg subcommand2
Output of subcomman2

The program is written in C 11 and compiled with CMake (3.10 ).

Now, I'd like to add another optional command, say optional_subcommand. Optional - in a sense that a user can decide whether to compile program with it when configuring Cake. To clarify, when the code is not compiled withoptional_subcommand support, the output should be something along this lines

$ prg optional_subcommand
Option not supported...

The optional_subcommand requires external library to be installed. Hence find_package(SomeLib REQUIRED) must be invoked at some stage by CMake. The code for optional_subcommand requires this library to compile.

All I can think of is writing some dummy code for optional_subcommand which is then replaced on request by CMake. I think this can be achieved be asking CMake to overwrite, say optional_subcommand.cpp with either dummy or not.

Is proposed solution sensible or perhaps there is a better way to achieve this?

CodePudding user response:

CMake can define a preprocessor symbol and add extra files to your target (below, prg) if needed:

if(SomeLib_FOUND)
  target_compile_definitions(prg PUBLIC HAVE_SOMELIB)
  target_sources(prg PRIVATE src/optional_subcommand.cpp)
endif()

You can then wrap the command dispatching code for optional_subcommand with #ifdef HAVE_SOMELIB.

  • Related