简体   繁体   中英

CMake - integrating options into C++ source files

I'm working with an existing project and cleaning up the CMake for it. However, right now I'm a bit confused by how exactly to go about integrating the CMake options into the actual source code.

For simplicity's sake, let's say I'd like to only execute one chunk of code, let's say cout << "print"; , inside example.cpp if, on CMake, the value ENABLE_PRINT is set to ON .

The project directory will look like this:文件夹布局

Using the above example, I did the following:

  1. On the parent project CMakeLists.txt , I added OPTION( ENABLE_PRINT "Enable Print" ON)
  2. Then, on the example subproject source folder Config.h file, I added #define ENABLE_PRINT
  3. On the Config.h.in located in the example subproject , I added #cmakedefine ENABLE_PRINT
  4. Finally, on the source file example.cpp , I encircled cout << "print"; inside #ifdef ENABLE_PRINT and #endif

After making those changes, the project will configure and generate just fine. However, when I make the software, it will error and essentially tell me that the chunk of code I encircled with #ifdef was not executed at all; it was ignored. In other words, the above steps I took did not do anything except "comment out" the chunk of code I wanted to make conditional upon ENABLE_PRINT.

So, how would I make this work?

You may combine option and add_definitions of cmake like here . Since a simple example is clearer than a long text here is a little main.c :

 #include<stdio.h>

 int main(int argc, char *argv[])
 {
   printf("start\n");
   #ifdef USE_DEBUG
     printf("Using debug\n");
   #endif
   printf("end\n");
   return 0;
 }

The CMakeLists.txt is :

cmake_minimum_required (VERSION 2.6)
project (HELLO) 

option(WITH_DEBUG "Use debug" OFF)

if (WITH_DEBUG)
  MESSAGE(STATUS "WITH_DEBUG")
  add_definitions(-DUSE_DEBUG)
endif()

add_executable (main main.c) 

You can try it by typing cmake . or cmake . -DWITH_DEBUG=ON cmake . -DWITH_DEBUG=ON then make and ./main

@francis answer is good, however I would also recommend using compile_definitions instead of add_definitions as well as specifying target for modern cmake modularity:

cmake_minimum_required (VERSION 2.6)
project (HELLO) 

option(WITH_DEBUG "Use debug" OFF)

add_executable (main main.c) 

if (WITH_DEBUG)
  MESSAGE(STATUS "WITH_DEBUG")
  target_compile_definitions(main PRIVATE USE_DEBUG)
endif()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM