Unnamed namespaces are not allowed in header files

# T017

# Unnamed namespaces are not allowed in header files

Description:

Unnamed namespaces are not allowed in header files.

The typical use of unnamed namespace is to hide module-internal names from the outside world. Header files are physically concatenated in a single translation unit, which logically merges all namespaces with the same name. Unnamed namespaces are also merged in this process, which effectively undermines their initial purpose.

Use named namespaces in header files. Unnamed namespaces are allowed in implementation files only.

Compliance: Boost

Show source code for this rule

Hide source code

    # Unnamed namespaces are not allowed in header files

    foreach fileName [getSourceFileNames] {
        set extension [file extension $fileName]
        if {[lsearch {.h .hh .hpp .hxx .ipp} $extension] != -1} {

            set state "start"
            foreach token [getTokens $fileName 1 0 -1 -1 {namespace identifier leftbrace}] {
                set type [lindex $token 3]

                if {$state == "namespace" && $type == "leftbrace"} {
                    report $fileName $namespaceLine "unnamed namespace not allowed in header file"
                }

                if {$type == "namespace"} {
                    set namespaceLine [lindex $token 1]
                }

                set state $type
            }
        }
    }

Rule index