Tag Archives: macro

It’s Time to Use #pragma once

In my opinion, preprocessor macros and the outdated #include mechanism are one of the worst parts of the C++ language. It is not just these things are causing a lot of problems, even more, it is very time consuming to find them.

This article will focus on #pragma once. In the past, I already wrote articles about how to avoid macros and why you should use namespaces.

While I usually focus on embedded development on this blog, this topic especially aplies to desktop software. It is valid not only for C++, but also C programs.

As usual, I try to cover the topic in detail to bridge any knowledge gaps you may have.

What is the Problem with Macro Header Guards?

Macro based header guards can lead to unexpected problems. In the following sections, I will explain the core concepts and demonstrate the problem using a simple example.

Compiling Units

In C and C++ a compile unit usually consists of a header (.h or .hpp) and implementation file (.c or .cpp). It is the lowest level of encapsulation. The header file contains the interface of the unit, while the cpp or c file contains the implementation.

Continue reading It’s Time to Use #pragma once

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 Avoid Preprocessor Macros