I am struggling with my first steps in C++. Already asked this question, but did not get the full answer specifically about namespace.
I did the following.
Source.cpp
#include <iostream>
using namespace std;
int PrintHello();
extern int tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
PrintFunc.cpp
#include <iostream>
using namespace std;
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
This is compiling perfectly. Now I am learning about namespaces, so I just tried to put the contents of the second file in a namespace as follows.
PrintFunc.cpp (modified)
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
}
And now I modified the Source.cpp also to reflect the namespaces introduction in the previous snippets.
#include <iostream>
using namespace std;
int MyNameSpace::PrintHello();
extern int MyNameSpace::tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
This simply does not compile. Can someone please kindly correct me. My objective is to understand namespace concept in c++. Also I have good exp with C#.
The problem that compiler does not know about namespace MYSpace
when compiling Source.cpp
.
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
But this sample is useless
. It work only because you have only one consumer .cpp
.
You should use .h
file and then include it (PrintFunc.h
) in Source.cpp
and any other .cpp
when you want to use that funtions.
I'll write an example:
Print.h
#pragma once
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
Notice that we dont't use additional includes
and using namespace
here. We would use includes
only to use some classes in functions
interfaces
.
using namespace
could "spoil" consumer's .cpp
or .h
.
Print.cpp
#include <iostream>
#include "Print.h"
using namespace std;
int MyNameSpace::tempCount = 111;
int MyNameSpace::PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
Here we can set any include
it will not touch any other files.
And consumer .cpp
:
#include <iostream>
#include "Print.h"
using namespace std;
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
VS specific: #pragma once
and for VS you have to #include "stdafx.h"
at first line in any .cpp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With