Reputation: 35213
I have 2 .cpp files
a1.cpp
#include <iostream>
#include <conio.h>
using namespace std;
using namespace te;
int main(int argc, char ** argv)
{
A a1(5);
cout<<a1.display();
return 0;
}
a2.cpp
#include <iostream>
namespace te
{
class A{
int i;
public:
A(int a)
{i = a;}
int display()
{
return i;
}
};
}
How do I use te in a1.cpp? Can I do it using header files?
Upvotes: 3
Views: 282
Reputation:
#include <iostream>
#include <conio.h>
#include "a2.cpp"
int main(int argc, char ** argv)
{
te::A a1(5);
std::cout << a1.display() << std::endl;
return 0;
}
This implies that a2.cpp
is in the same folder as a1.cpp
. It should be better though to make it a header file.
You should keep in mind that that it is generally to be avoided using namespace XX;
and you should just have straight stuff. eg std::cout
It should be noted that conio.h
is not part of standard C
edit: and you are also using cout
which is C++
. You should try to avoid mixing the two Languages (Credits to DeadMG for clarification, see comment)
Upvotes: 2
Reputation: 3046
It seems to me that your question is more about headers than namespaces: you already do use the namespace te
in your a1.cpp (using namespace te;
). The problem is the visibility of the class te::A
for which you need to put its definition into a header and #include
it. Without this, there is no way for the compiler to know that you have your class defined in a2.cpp when it compiles a1.cpp (each .cpp is compiled separately).
Upvotes: 1
Reputation: 73433
Yes, you require a2.h
. Add namespace te{ class A { public: A(int a); int display();};}
in the header file and include the header file from a1.cpp
Upvotes: 1
Reputation: 238
Just put Class A to header under namespace te and let a1 include it.
Upvotes: 1