You, the programmer, create a file and declare the namespace.
A namespace is often locked away in a header file with various function prototypes and class declarations. The implementation is often in the C++ file that acts as the object code. For example:
Code:
// namespace_example.h
#ifndef _NAMESPACE_EXAMPLE_H_
#define _NAMESPACE_EXAMPLE_H_
#include <iostream>
namespace example_foo {
template <typename T>
void print (const T& t) { std::cout << t << std::endl; }
void print ( void );
}
#endif Code:
// namespace_example.cpp
#include "namespace_example.h"
void example_foo::print () { print ("Hello World!"); } Code:
// tester.cpp
#include "ns_example.h"
#include <string>
using namespace example_foo;
using namespace std;
int main () {
float x = 2.4;
string str_bam = "Bam!";
print();
print("Hello user!");
print(x);
print((int)x);
print(str_bam);
return 0;
} Because the template was in the header, that was required to be implemented there (template implementation cannot be separated from declaration like functions, classes, etc. can be). The special case of no arguments passed to the print() function is implemented in namespace_example.cpp. Of course, I could have implemented it in the header file (namespace_example.h), but I wanted to illustrate how things work.
The prototype for the function print() with no arguments is in the header file while the implementation is in the C++ file "namespace_example.cpp". Also note that in the C++ file, I used "void example_foo::print ()" rather than just "void print ()". This is because I haven't used a using directive to say that print() belongs to the example_foo namespace. However, I didn't need to use it when I called print("Hello World!"); in the function body. This is because I was already allowed to access the namespace. Any member of a namespace has access to any other member of the same namespace. Also note that that C++ file had no int main() function. That's because we don't want to run it. We just need the code inside.
In the tester program, I used two using directives to allow me to use std::string without using "std::" and "example_foo::print" without using "example_foo::". Why didn't I do that in the other files? Basically, the whole idea behind namespaces would be ruined. If you create your own class called "string" and you have "using namespace std;" at the top with <string> included, the compiler will wonder which one you meant.
Anyway, this post is long enough. Just know that namespaces are declared in a file. You can add to that namespace across multiple files if you need to however. For example, "namespace std {" can wrap the entire <istream> header (other than certain C preprocessor directives like #include) as well as it can wrap around the entire <string> header.
