Menu Close

Month / October 2014

How and Why to Avoid Preprocessor Macros

While most naming conflicts in C++ can be solved using namespaces), this is not true for preprocessor macros.

This post is outdated. You will find an updated version here:
How and Why to Avoid Preprocessor Macros

Macros can not be put into namespaces. If you would try to declare a new class called Stream, but somewhere in a header you include would be a macro called Stream, things would break. While compiling your code, the preprocessor would simply replace the Stream in your class Stream { declaration. You could get a really confusing error message, and it would take time and energy to find the actual problem.

Especially people developing software for controllers, often overuse macros for almost everything. They believe it will save RAM, speed up the code or make it more flexible. Often none of these three things are true. Actually each additional macro is a risk for name conflicts and makes the code less readable. You should reduce the use of macros to the absolute minimum, and especially avoid macros in your header files.

Continue Reading

How and Why to use Namespaces

Namespaces are a feature of C++ which address the problem of name conflicts. There is a “global” namespace, where everything lives which was declared without namespace. Especially the Arduino environment declares a huge amount of variables and constants there, so it is a good practice to put everything you write in a own namespace. Namespaces are only used while compile time, and they do not use any memory at runtime nor make they run your program slower.

In my case I choose the namespace lr which stands for Lucky Resistor. Everything I declare in this namespace is accessible trough the :: operator which you probably already know from function definitions.

Continue Reading