Reputation:
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.
Upvotes: 3
Views: 191
Reputation: 23
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):
You can explicitly call out the namespace using ::
like you did:
printf ("%d", a::main1());
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).
Upvotes: 0
Reputation: 8709
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());
}
Upvotes: 1
Reputation: 190897
You have to declare the namespace, class and function in a header file and include it in the test2.cpp
file.
Upvotes: 4