Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable parts of code when compiling

Tags:

c++

The scenario is as follows, I have 10+ different projects all using a logging framework and it is a requirement in desktop systems and for research projects that the logging framework actually logs. However, we want to deploy the same code in embedded devices without the logging as it is not needed and does affect performance (lots of log statements).

How can I say compile for desktop = enable logging or compile for embedded = disable logging?

I have looked at ifdef but not sure that that is the best way forward

I use waf as my build system and we use C++17 if that helps.

like image 892
Lars Nielsen Avatar asked May 09 '19 06:05

Lars Nielsen


2 Answers

You have two options: preprocessor and source choice.

Preprocessor is #ifdef, usually by defining a macro in different variants depending on platform, like this:

#if defined(EMBEDDED)
#  define LOG(msg)
#else
#  define LOG(msg) log(msg)
#endif

and then using the macro to log things:

LOG("I'm here");

The macro can of course be more complex.


Source choice means, basically, that you replace your logging library with a substitute that has the same interface, but does nothing.

Source choice is easier to manage and a bit cleaner to use, but not as flexible or thorough. For really minimizing your executable size, you probably want to go the preprocessor way.

like image 86
Sebastian Redl Avatar answered Sep 25 '22 00:09

Sebastian Redl


Source choice would still make the calls to the function so for an embedded system may not be the most optimized. You might also be able to change the path to enable source choice instead of copying libraries in/out.

like image 27
Devajoy Choudhury Avatar answered Sep 25 '22 00:09

Devajoy Choudhury