3

I have a file named test1.cpp

namespace a {
int main1() {
    return 3;
}
}

And I have another file test2.cpp

#include <stdio.h>
using a::main1;
int main() {
    printf("%d", a::main1());
}

Then I got a compilation error saying 'a' has not been declared with g++. Please help me to find out what I missed here, and normally how to do this.

Thank you.

3 Answers 3

4

You have to declare the namespace, class and function in a header file and include it in the test2.cpp file.

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

1 Comment

You could even declare the name space and class or function in the same file, but that is bad practice. Declarations should go into header files.
1

You need to declare your a::main1 in a header file, call it test1.h, and then include that header in test2.h. Otherwise test2 has no way of knowing what you've decalared in test1.

test1.h

namespace a {
int main1();
}

test1.cpp

namespace a {
int main1() {
    return 3;
}
}

test2.cpp

#include <stdio.h>
#include test1.h
using a::main1;
int main() {
    printf("%d", a::main1());
}

Comments

0

Your function main1() is declared in the namespace 'a', so when you call it in the printf() you need to make sure the compiler knows what namespace to look it up in. There are two ways to do this (that I know of):

  1. You can explicitly call out the namespace using :: like you did:

    printf ("%d", a::main1());
    
  2. Or you can, somewhere above it's first use, tell the compiler to generally look for symbols in the 'a' namespace by using the line:

    using namespace a;
    

The compiler I'm using (MS Studio 2008) did not complain when I used both techniques together.

I believe the reason you got the error you did was that your "using" statement was not correctly formed for the compiler (see above).

2 Comments

surely his problem is that test2 doesn't include test1 so the namespace is unknown?
Nope. The other two answers (as of this moment) miss the mark (in fact the one which included code would not compile without error). THE PROBLEM IS the "using" statement is mis-formed! No C/C++ compilers (that I know of) care whether something is in a header or the cpp file, it just needs to be able to see and parse it according to the language rules. I do agree, however, that it is generally best practice to declare things in headers - keeps things well organized, and thus maintainable.

Your Answer

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