user1096734
user1096734

Reputation:

c++ namespace from different source file

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

Answers (3)

Michael E. Morris
Michael E. Morris

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):

  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).

Upvotes: 0

StevieG
StevieG

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

Daniel A. White
Daniel A. White

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

Related Questions