Search code examples
c++qualified-name

Invalid use of qualified name


I'm trying the following:

#include <iostream>

namespace A
{
    extern int j;
}

int main()
{
    int A::j=5;
    std::cout << A::j;
}

But I've error: invalid use of qualified-name ‘A::j’. Please explain why this error occurred?


Solution

  • Please explain why this error occurred?

    The language simply doesn't allow you to define namespace-scope variables inside functions. The definition has to be either in namespace A:

    namespace A {
        int j = 5;
    }
    

    or in the surrounding (global) namespace:

    int A::j = 5;
    

    You can, of course, assign a value to the variable inside the function:

    int main() {
        A::j = 5;
        // ...
    }
    

    but you'll also need a definition somewhere, since your program doesn't have one.