I’m having some trouble understanding the preprocessor and namespaces in C++. For example, consider the following program:
#include <iostream>
int main()
{
using namespace std;
cout << "Hello World!" << endl;
return 0;
}
So when this program is getting ready to be compiled, the preprocessor will recognize the #include directive and add the iostream file to the program so that the program will have I/O capability (ie “cout” and “endl”). Now according to my textbook the classes, functions, and variables that are a standard component of C++ compilers are placed in the namespace std.
This is confusing because if the standard functions (“cout” and “endl”) are placed in this namespace what is the purpose of iostream? I’m basically trying to understand why we need both iostream and some information about the namespace in use.
Strictly speaking, you do not need
using namespace std;All it does is letting you writeinstead of
The namespace “contains” iostream definitions (among other definitions provided by the standard C++ library) only in the sense that
std::is implicitly “prefixed” to all names. This “contains” is different from the “contains” in “theiostreamfile contains definitions of input/output functions”: the file literally contains the definitions; thestd::namespace name is only a prefix that lets you avoid name collisions.