The extern Keyword

After all the recent posts about statics, I wanted to talk about the extern keyword before moving onto something different.

Do you remember the problem we had with our “global” static variable in this post? If you haven’t read it, the code example illustrated that static variables are only available to code in the translation unit. That means that if you include a file with a static variable in several of your other files, you won’t just have one copy of that variable. This is really important, because you could run into a nasty bug if you are accessing the static variable thinking that it is the same one across all the files you are using it in.

The extern keyword provides the solution to this, as it allows you to create a true global variable that will be available across all files and all translation units.

Read moreThe extern Keyword

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