I need to conditionally compile several parts of code, depending on whether there are some libraries present on the system or not. Their presence is determined during the CMake configuration phase and I plan to tell the compiler the results using preprocessor definitions (like #ifdef(LIB_DEFINED) … #endif).
I know about two possibilities how to achieve that in CMake:
- Ceate a template file with these preprocessor definitions, pass it in CMakeLists to configure_file() and finally #include the produced configuration file in every source file
- Directly use add_definitions(-DLIB_DEFINED) in CMakeLists.
The first approach seems more complicated to me, so are there any advantages of taking it instead of the second one (e.g. avoiding some portability issues)?
Depending on the amount of libraries you use, the call of the compiler becomes large if following the second approach. So I would say for smaller projects with only 2-3 of those optional libraries follow approach 2 but if it’s more like 10 or so, better follow approach 1 so that the compilation output stays readable.