TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  STA#002Checked automatically with code checker

Synopsis:Objects with static storage duration should be declared only within the scope of a class, function, or unnamed namespace
Language:C++
Severity Level:4
Category:Static Objects


Description:

This means that declarations of global objects with external linkage are best avoided. Otherwise, such external declarations are only allowed in header files.

Apart from the well known problems related to the use of global data, the order in which constructors of global objects are called at program startup is only specified within each translation unit, but not across different translation units (say, source files). This can be problematic in case the construction of a global object depends on the construction of another global object in a different file. See further the ISC++ explanation.

Note that the term "unnamed namespace" is preferred to "anonymous namespace".

Classes defined outside any namespace or block should be avoided where possible, and prefixed otherwise. The following example (using condensed style for brevity) shows undefined behaviour if the resulting objects are linked together.

// file1.cpp
#include <iostream>
// A simple class definition at "file scope".
// This does not hurt anyone, does it?
    class Demo
    {
    public:
         Demo(int m) : v(m) 
	     { std::cout << "construct " << v << std::endl; }
         ~Demo() 
	     { std::cout << "destroyed " << v << std::endl; }
    private:
        int v;
    };

int main (int argc, char *argv[])
{
    Demo dd(7);
    extern void badPractice();  // should come from a header...
    badPractice();
    std::cout << "done ----------" << std::endl;
}

// file2.cpp
#include <iostream>
// Another class definition at "file scope".
class Demo
{
public:
     Demo(double m) : v(m) 
	 { std::cout << "# construct " << v << std::endl; }
     ~Demo() 
	 { std::cout << "# destroyed " << v << std::endl; }
private:
    double v;
};

// a declaration of this function should go into a header
void badPractice()
{
    Demo foo(3.14);     // foo has no linkage
    std::cout << "# done ----------" << std::endl;
}

In case compilers do not support the "namespace" concept yet, objects at file scope may also be declared with the "static" keyword.



Literature References:
ISC++ Rec. 9.1