简体   繁体   中英

How do I define a variable in a namespace with “using namespace”?

So I have a namespace thing with extern int variables declared in a header. I'm trying to define them in a.cpp with using namespace thing; to simplify initialization, but it doesn't seem to work the way I expected when trying to define a variable in thing.cpp . What gives?

main.cpp:

#include <cstdio>
#include "thing.hpp"

int main()
{
    printf("%d\n%d\n",thing::a,thing::func());
    printf("Zero initialized array:\n");
    for(int i = 0; i < 10; i++)
        printf("%d",thing::array[i]);

    return 0;
}

thing.hpp:

#pragma once

namespace thing {
    extern int
        a,
        b,
        array[10];
    extern int func();
}

thing.cpp

#include "thing.hpp"

using namespace thing;

// I wanted to do the same thing with 'a' for all variables
int a,thing::b,thing::array[10];

int thing::func() {
    return 12345;
}

error:

/tmp/ccLbeQXP.o: In function `main':
main.cpp:(.text+0x11): undefined reference to `thing::a'
collect2: error: ld returned 1 exit status

using namespace thing allows you to use identifiers from the thing namespace without prefixing them with thing:: . It effectively pulls them into the namespace where the using directive is (or the global namespace).

It doesn't put further definitions into the namespace thing . So when you define int a; , it's just in the global namespace. You need to use int thing::a; or namespace thing { int a; } namespace thing { int a; } to define it in the namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM