Tag Archives: namespace

Class or Module for Singletons?

Should you use a class or a module with a namespace for a singleton interface in your firmware? I found there are many misunderstandings which lead beginners to make a wrong decision in this matter. With this article, I try to visualize these misunderstandings with simple example code for the Arduino platform.

Before we start, as with all of these topics, there is no simple rule, and there are a lot of exceptions. In the end, it heavily depends on the compiler and architecture you use.

The Example Use Case

I like to write simple driver code for my firmware, which flashes two LEDs for a given duration. The used PINs for the LEDs shall be configurable. In my main loop, I will flash the two LEDs at different durations.

The use case is no real-world example, but it contains all elements of configuration, initialization and usage.

Using a Simple Class

For the first test case, I write a simple class, without constructor and all required methods for the use case.

Continue reading Class or Module for Singletons?

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 at compile time, and they do not use any memory at runtime or make 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 How and Why to use Namespaces