head.h
#pragma once
namespace foo
{
int bar;
int funct1();
}
head.cpp
#include \"head.h\"
int foo::funct1()
{
Do carefully note that foo
is not a class, but a namespace. When you declare a free variable in the header file:
int bar;
And then #include this header file multiple times (into different CPP files, causing multiple translation unit compilations), you'd get a linker error. Everyone knows it.
And, you'd add extern
attribute at the declaration, and define the variable elsewhere in one of the CPP/C file.
Putting a global variable into a namespace is nothing but giving the global variable a different name. Think if foo::bar
as foo__NS__bar
, and hence you must add extern
in the header and define foo::bar
at some locatoin.
Note that this is different from a non-static member variable of a class. A class variable doesn't need to be defined/declared this way since the class is a type. Each instantiated variable of class-type would have a separate copy of the variable.
Further to that, when you add a static
variable in the class, you are giving that logically global variable another name. Thence, you must have that static-variable defined one of the CPP file.