assignment_operator
assignment_operator

Reputation: 1365

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: folder layout

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?

Upvotes: 6

Views: 3408

Answers (2)

greygore
greygore

Reputation: 94

@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()

Upvotes: 3

francis
francis

Reputation: 9817

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 then make and ./main

Upvotes: 11

Related Questions