Rule Definition
An anonymous namespace will be unique within each translation unit. Any declarations appearing in an anonymous namespace in a header will refer to different entities in each translation unit, which may not be consistent with developer expectations.
Production quality C++ code uses header files to share code between translation units through #include directive. If an anonymous namespace is defined then each translation unit will define its own instance of the unnamed namespace. This may cause:
Unexpected behavior, undefined behavior and may bloat the resulting executable
Remediation
Namespaces in header files should always be named.
Violation Code Sample
// Header.hpp
namespace // Non-compliant
{
extern int32_t x;
}
// File1.cpp
#include "Header.hpp"
namespace
{
int32_t x;
}
void fn_a ( void )
{
x = 24;
}
// File2.cpp
#include "Header.hpp"
namespace
{
int32_t x;
}
void fn_b ( void )
{
fn_a ( );
if ( x == 24 ) // This x will not have been initialized.
{
}
}
Reference
Standards Reference
MISRA C++ 2008, 7-3-3: There shall be no unnamed namespaces in header files
Related Technologies
Technical Criterion
Programming Practices - Modularity and OO Encapsulation Conformity
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.