0

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
7
  • 1
    Did you compile and link thing.cpp to your final program? Commented Jan 16, 2021 at 22:06
  • @πάνταῥεῖ Yeah, the code works fine when I use thing::a instead of just a Commented Jan 16, 2021 at 22:10
  • Sure, you must fully qualify your symbol names, unless you do using thing::a; statements for all the symbols defined in the .cpp file. Commented Jan 16, 2021 at 22:11
  • @πάνταῥεῖ So what rule makes it so I can't use using namespace thing? If I include iostream in the header, and using namespace std in the .cpp I can use it's functions/methods without the std namespace prefix just fine Commented Jan 16, 2021 at 22:17
  • Why not wrap the contents of thing.cpp in namespace thing { ... } like you did with thing.hpp? Commented Jan 16, 2021 at 22:26

1 Answer 1

1

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; } to define it in the namespace.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, I've changed the question title to match the answer I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.