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.

How to share code on your blog using github.

Suppose that you have a piece of code that you want to share on your blog (or other source). If you have a github account, than you can easily share it.

Go to gist.gitbub.com and type the piece of code you want to share. Then, just copy and paste the address. The end result is something like this.

#include <iostream>
int main()
{
std::cout << "Hello world!\n";
return 0;
}
view raw helloworld.cpp hosted with ❤ by GitHub

That’s all. A full explanation for wordpress sites can be found here https://wordpress.com/support/gist/.

Happy coding!