Conditional compilation with macros using CMake

As I have described in my previous post, I am working through the 2nd edition of Discovering Modern C++ by out advantage of being able to write the output to file for example… besides sometimes I find it more convenient.

On the other hand, printing “i = 8 in function f” is not something you usually want your program to do, even in debug mode. Deleting or commenting out these statements and then adding them again, was too annoying to me. Besides, this time I have decided to learn CMake, as it seems to be the standard build system at the moment. I also found it really helpful tool for managing files associated with the book as single project and not have dozens of projects for every toy program I write while reading the book.

So, I used CMake to automate the process.

Logging function calls and variable values, is actually easy – it just requires a bit of conditional compilation (similar to Debug/Release mode when using asserts…).

How is it done?

Before every message we want to print, you do something similar to this

#ifdef PRINT_STATEMENTS_ON
// print statements
#endif

When compiling, pass -DPRINT_STATEMENTS_ON flag to the compiler. So far easy. But what happens if we want to make this option available in few projects?

We add the following lines to CMakelists.txt file.

option(WITH_PRINT_STATEMENTS "Print local variables values and invoked function names" OFF)
if(WITH_PRINT_STATEMENTS)
    add_definitions(-DPRINT_STATEMENTS_ON)
endif()

WITH_PRINT_STATEMENTS default value is OFF because printing local values is not the default behavior we want.

To set it on, when invoking add -DWITH_PRINT_FUCNTION_MESSAGES=ON flag when building (or to your configuration, if you use IDE, for example).

In order not add the folders that do not need this functionality, put

if(NOT WITH_PRINT_STATEMENTS)
# Add subdirectories of projects that do not need this functionality
# Or add executables without this functionality
endif()

Perhaps, there might be better ways to do this (feel free to write in comments), however this one was simple to implement and understand.

Hope it helps someone.

Leave a comment