Pergunta

I have created a noname namespace with some variables inside in header, want to initialize them in .cpp and see in main.cpp. A noname namespace i am expecting to work just fine without mentioning this namespace in .cpp. However I get error as if in .cpp I had totally new a and b. Anyone has idea how to resolve it?

xx.h

namespace
{
    int a;
    int b;
}

.cpp

#include "xx.h"
a = 5;
b = 10;

main.cpp

#include <iostream>
#include "xx.h"
int main()
{
       std::cout << "values" << a << b << std::endl;
}
Foi útil?

Solução

You may not use assignment statements outside functions. You may only declare or/and define objects . So the valid code will be

namespace
{
    int a = 5;
    int b = 10;
}

main.cpp

#include <iostream>
#include "xx.h"
int main()
{
       std::cout << "values" << a << b << std::endl;
}

Take into account that objects declared in unnamed namespaces have internal linkage. It means that if this header is included in more than one module then in each module it declares a separate namespace.

Consder the following example

unnamed.h

namespace
{
    int a = 5;
    int b = 10;
}

void f();

second.cpp

#include <iostream>
#include "unnamed.h"

void f()
{
    a = 10; b = 5;
    std::cout << "a = " << a << ", b = " << b << std::endl;
}

main.cpp #include #include "unnamed.h"

int main()
{
    f();
    std::cout << "a = " << a << ", b = " << b << std::endl;

    return 0;
}

The output is

a = 10, b = 5
a = 5, b = 10

Outras dicas

The problem is not with the anonymous namespace. Variables cannot be assigned at global scope.

// At global scope
int num;

num = 10;  // Error. You are doing something similar.

Either initialize the variables in the namespace itself or assign them values in a function.

your header has to declare them as extern and in cpp you have to define them. (otherwise any including file will create their own a and b)

this may work (quite not sure because of anonymous namespace):

xx.h

namespace
{
    extern int a;
    extern int b;
}

.cpp

#include "xx.h"
int a = 5;
int b = 10;

main.cpp

#include <iostream>
#include "xx.h"
int main()
{
       std::cout << "values" << a << b << std::endl;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top