Hauptinhalt

Cpp.Namespace Class

R2026b

Namespace: Cpp

Represent namespaces in your code

Since R2026a

Description

Namespace class represents the C++ namespaces in your code.

Predicates

expand all

Examples

collapse all

Consider this code:

#include <iostream>

int globalCounter = 0; // 

namespace myns {
    int localCounter = 0;
}

int main() {
    std::cout << globalCounter << std::endl;
    std::cout << myns::localCounter << std::endl;
    return 0;
}
The variable globalCounter is defined in the global namespace. Use the predicates of this class and detect this pattern. Copy the code in the file src.cpp for later use.

  1. In a new folder Namespace, initialize a new coding standard. At the command line, enter:

    polyspace-query-language init

  2. In the file main.pql, enter this content:

    package main
    
    // Main PQL file defines the catalog of your PQL project.
    // The catalog is a collection of sections.
    catalog namespaceExample = {
        #[Description("Example Section")]
        section ExampleSection = {
            #[Description("variable declared in global namespace"),Id(myRule)]
            rule ExampleRule = {
                defect Exampledefect =
                when Cpp.Variable.is(&variable)
                and variable.namespace(&ns)
                and ns.isGlobal()
                and variable.name(&vname)
                raise "Variable global namesapce detected: \"{vname}\""
                on variable
            }
        }
    }
    

  3. Create the coding standard Namespace.pschk using this command at the command line:

    polyspace-query-language package

  4. Using the generated coding standard, run a Bug Finder analysis on your source file. For example, at the command line, enter:

    polyspace-bug-finder -sources src.cpp -lang cpp -checkers-activation-file Namespace.pschk
    The analysis reports defects on the variable globalCounter.

Version History

Introduced in R2026a