Static Variables in C and C++ – File Level

When is a global not a global? When it’s a static variable.

This post, and the next three, will talk about static variables. Let’s start with static variables declared in a file.

Static variables in a file

If you declare a static variable at file level (i.e. not inside any other code), then you are creating a so-called “global” variable that will:

  1. be available for the entire duration of your program, and
  2. be accessible only from that translation (compilation) unit (i.e. the file itself and any file that includes it).

Number two is the important one here. It means that if you include (say) a header that contains a static variable in two different source files, you will end up with two “global” variables with the same name.

Read moreStatic Variables in C and C++ – File Level

Friend Functions And Classes In C++

The friend keyword in C++ is one of those concepts that is formally taught, but then seems to disappear off the scene once you get into the real world. Maybe friends are less common in embedded programming (ha ha), but I’ve seen very few of them over the years.

The thing is, they just don’t seem to be at the forefront of people’s minds when writing code. When would you ever actually use one of these things?

Aren’t they just a way to avoid writing getters and setters??

I think when you are learning a language, understanding concrete examples of why a concept is there is absolutely necessary if that concept is to stick and be used well.

So let’s have a look at friend functions and classes and see what on earth we could do with them.

Read moreFriend Functions And Classes In C++

Inclusion Guards

Just to clear up what we’re talking about, an inclusion guard looks like this:

#ifndef HEADER_FILE_H
#define HEADER_FILE_H

...//your header

#endif //HEADER_FILE_H

It consists of three preprocessor directives around the code of your header file.

Most IDEs add these for you automatically when you create a header, but it’s well worth having an appreciation of why they are there.

Read moreInclusion Guards

What Does The Preprocessor Do?

What a jolly good question.

The preprocessor takes a look at your source code just before it goes off to the compiler, does a little formatting, and carries out any instructions you have given it.

Like what?

Well, preprocessor instructions are called preprocessor directives, and they all start with a #.

Like #include?

Exactly.

Each # command that the preprocessor encounters results in a modification to the source code in some way. Let’s take a look at them briefly in turn, and then we’ll see what goes on behind the scenes.

Read moreWhat Does The Preprocessor Do?