CRITICAL
Rule Definition
When defining a static variable in a header file, a new instance of the variable is created for each file including the header file. This is often surprising as people often expect to have only one instance of the variable. This leads to errors that are very difficult to track/understand.
Remediation
Do not define the variable in header as static but define it as static in a source file (ex: *.c, *.cpp) and as extern in files using it instead.
In the particular case of "static const variable=value;", just remove the static, it is redundant with the "const" qualifier.
Violation Code Sample
FILE: f.h
static int myvar = 0;
FILE: f2.cpp
#include "f.h"
void g() {
myvar = 1;
}
FILE: f1.cpp
#include "f.h"
void g();
int main(int argc, char* argv[]) {
g();
printf("myvar value is %d\n", myvar); /* We expect 1 to be displayed, but it is not the case.. */
return 0;
}
Fixed Code Sample
FILE: f.h
extern int myvar;
FILE: f2.cpp
#include "f.h"
void g() {
myvar = 1;
}
FILE: f1.cpp
#include "f.h"
int myvar = 0;
void g();
int main(int argc, char* argv[]) {
g();
printf("myvar value is %d\n", myvar); /* Display 1 as expected. */
return 0;
}
Related Technologies
C++
Technical Criterion
Programming Practices - Structuredness
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.