add_definitions vs. configure_file
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 fi开发者_运维问答le 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)?
Approach 1 is often preferable as you can also install that file as a configured header, allowing other projects using/linking to your code to use the same settings. It is also possible to inspect the file and see how the project is configured. Both approaches will work, and occasionally add_definitions is the better approach (one or few definitions, no advantage in preserving those definitions after initial compilation).
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.
精彩评论