BRIEF: is it ever safe to do
namespace Foo {
#include "bar"
}
Before you blithely say no, I think I have some rules that allow it fairly safely.
But I don't like them, since they require the includer to separately include all global scope headers needed. Although this mightr be tolerable, if we imagine including within a namespace to be just a special management feature.
And overall, externs and forward declarations just don't work well from within namespaces.
So I gues I am asking
a) What other gotchas
b) is there a better way
== A [[Header-only library]] ==
I like writing libraries. [[Header-only libraries and linker libraries]].
E.g.
#include "Valid.hpp"
defines a template Valid, for a simple wrapper type.
(Don't get bogged down in "You should use some standard library for this rather than your own. This is an exanple. I dunno if Boost or C++ have yet standardized this. I have been using wrappers since templates were added to C++.)
Also, let us say, it is a header only library, that defines, in Valid.hpp,
a print function
std::string to_string( const Valid& v ) {
std::ostringstream oss;
if( v.valid() ) { oss << v; }
else { "invalid"; }
return oss.str();
}
And because I think it is the right thing to do,
I have Valid.hpp include the headers it depends on:
Valid.hpp:
#include <iostream>
#include <sstream>
template<typename T>
class Valid {
private:
T value_;
bool valid_
...
};
...
std::string to_string( const Valid<T>& v ) { ...
So far, so good.
I can use Valid straightforwardly.
== Name collision - trying to use include within namespace to work around ==
But sometimes there is a collision.
Sometimes somebody else has their own Valid.
Namespaces to the rescue, right? But I don't want to change all of my existing code to use the namespace.
So, I am tempted, in a new project that has a collision, to do
namespace AG {
namespace Wrapper {
#include "lib/AG/Wrapper/Valid.hpp"
}
}
AG::Wrapper::Valid<T> foo_v;
...
PROBLEM: the headers included are no longer freestanding. Everything defined inside is no placed inside
namespace AG::Wrapper.
It's not hard to "fix".
Al we "must" do is include all the top level libraries that Valid.hpp depends on.
If they have include guards, they will not be re-included.
#include <iostream>
#include <sstream>
namespace AG {
namespace Wrapper {
#include "lib/AG/Wrapper/Valid.hpp"
}
}
AG::Wrapper::Valid<T> foo_v;
...
But it is no longer freestanding. :-(
Worse, sometimes the header-only library contains extern declarations and forward declarations of stuff outside itself.
These declarations get placed inside the namespace too.
In particular, if the extern declarayion is inside a function defined in the namespace.
I.e. sometimes we use extern and forward declarations, rather than included an entire header file.
These get included in the namespace.
Q: is there a better way?
== :: doesn't do it ==
Hint: :: doesn't do it. At least not all the time, not in gcc 4.7.2.
(Gcc's behavior in this has changed over time. Gcc 4.1.2 behaved differently.)
E.g.
Type var;
namespace Foo {
void bar() {
extern ::Type ::var;;
extern ::Type ::Foo::bar;
extern ::Type::foo ::bar; // see the ambiguity?
};
But it's not just the ambiguity.
int var;
namespace Foo {
void bar() {
extern int var;
};
works - Foo::bar'svar is equal to ::var.
But it only works because of the declaration outside the namespace.
The following doesn't work
header
int var;
cpp
namespace Foo {
void bar() {
extern int var;
}
}
although the following does:
header
int var;
cpp
void bar() {
extern int var;
}
}
Basically, what this amounts to saying is that
it is not a trivial refactoring to put functions inside a namespace.
Wrapping a namespace around a chunk of code,
whether or not it is #include'd,
is not a sufficient.
... at least not if there are extern or forward declarations.
And even if you
== Opinion against putting includes within namespaces ==
Stackoverflow folks seem to be against putting #includes inside namespaces:
E.g. How to use class defined in a separate header within a namespace:
... you should never write a #include inside a namespace. Where "never" means, "unless you're doing something really obscure that I haven't thought of and that justifies it". You want to be able to look at a file, and see what the fully-qualified names are of all the things in it. You can't do that if someone comes along later and sticks an extra namespace on the front by including from inside their namespace. – Steve Jessop Jan 6 '12 at 16:38
Overall question:
Is there any way, from deep within a namespace,
to say "and now here are some names that I am depending on from the outside world, not within the namespace."?
I.e. I would like to be able to say
namespace A {
void foo() {
// --- here is a reference to gloal scope extreren ...
I know this is an old question, but I want to give a more detailed answer anyway. Also, give a real answer to the underlying problem.
Here's just a few things that can go wrong if you include a header from within a namespace.
The header includes other headers, which are then also included from within the namespace. Then a different place also wants to include these headers, but from outside the namespace. Because the headers have include guards, only one of the includes actually goes in effect, and the actual namespace of the stuff defined in the headers suddenly subtly depends on the order you include other headers.
The header, or any of its included headers, expects to be in the global namespace. For example, standard library headers will very often (in order to avoid conflicts) refer to other standard stuff (or implementation details) as ::std::other_stuff, i.e. expect std to be directly in the global namespace. If you include the header from within a namespace, that's no longer the case. The name lookup for this stuff will fail and the header will no longer compile. And it's not just standard headers; I'm sure there are some instances of this e.g. in the Boost headers too.
If you take care of the first problem by ensuring that all other headers are included first, and the second problem by making sure no fully qualified names are used, things can still go wrong. Some libraries require that other libraries specialize their stuff. For example, a library might want to specialize std::swap, std::hash or std::less for its own type. (You can overload std::swap instead, but you can't do that for std::hash and std::less.) The way to do this is close your library-specific namespace, open namespace std, and put the specialization there. Except if the header of the library is included in arbitrarily deeply nested namespaces, it cannot close those namespaces. The namespace std it attempts to open won't be ::std, but ::YourStuff::std, which probably doesn't contain any primary template to specialize, and even if it did, that would still be the wrong thing to do.
Finally, things in a namespace simply have different names than things outside. If your library isn't header-only but has a compiled part, the compiled part probably didn't nest everything in the namespace, so the stuff in the library has different names than the stuff you just included. In other words, your program will fail to link.
So in theory, you can design headers that work when included within a namespace, but they're annoying to use (have to bubble up all dependencies to the includer) and very restricted (can't use fully qualified names or specialize stuff in another library's namespace, must be header-only). So don't do it.
But you have an old library that doesn't use namespaces, and you want to update it to use them without breaking all your old code. Here's what you should do:
First, you add a subdirectory to your library's include directory. Call it "namespaced" or something like that. Next, move all the headers into that directory and wrap their contents in a namespace.
Then you add forwarding headers to the base directory. For each file in the library, you add a forwarder that looks like this:
#ifndef YOURLIB_LEGACY_THE_HEADER_H
#define YOURLIB_LEGACY_THE_HEADER_H
#include "namespaced/the_header.h"
using namespace yourlib;
#endif
Now the old code should just work the way it always did.
For new code, the trick is not to include "namespaced/the_header.h", but instead change the project settings so that the include directory points at the namespaced subdirectory instead of the library root. Then you can simply include "the_header.h" and get the namespaced version.
I don't think it's safe. You put all your includes into the namespace Foo...
Imagine some of your includes include something from the std namespace... I cannot imagine the mess !
I wouldn't do that.
Header files are not black boxes. You can always look at a header you're including in your project and see if it is safe to include it inside a namespace block. Or better yet, you can modify the header itself to add the namespace block. Even if the header is from a third-party library and changes in a subsequent release, the header you have in your project won't change.
Related
The question might be trivial (and possibly a duplicate).
As far as I understand, a C/C++ header file (with a using namespace in it), when used by other source files, it is copied right at the point where the #include directive was in that source file.
Also, given that a source file uses a relatively large number of include directives and that there may be a couple of "redefinitions" for the entire standard library (simply targeted at different implementations).
Here is the main question: How do I know which namespaces am I currently using at any point in the source file if the source file has no using namespace statement?
I'm reading through source files and I have no idea which namespace is being used.
One can override the namespace cleverness by using something like ::std::getline().
If there is no easy way of determining the namespace, is it fair to refactor those files, such that where say string is used to replace it with ::std::string?
If you don't have a using namespace ... directive you're not using any namespace. In general, your code should refer to things in the standard library with their full names, e.g., std::cout, std::get_line(), std::string.
Yes, you can save your self some typing at the expense of loss of clarity and sometimes mysterious compilation failures or, worse, runtime failures with using namespace std;. After that, you don't have to put std:: in front of the names of things in the standard library: cout, get_line(), string. The using directive puts those names into the global namespace, along with a bunch of sludge that you probably aren't interested in.
If you use something like using namespace std; it should appear only in a source file, never in a header. That way you can tell which namespaces have been "used" by looking at the top of the file. You shouldn't have to track through all your headers for stray using directives.
using namespace does not mean that you currently use this specific namespace. It means, that all types, variables and functions from this namespace are now in your global namespace, for this translation unit. So, you might have multiple of these statements.
This is why header files should never use using namespace. There is no easier way than using std::string within a header file, you should always be very explicit about the namespace without using namespaces.
Having used using namespace xxx, there is no way of finding out that xxx is now in global namespace, I am afraid.
using namespace does not do what you expect...
If you want to place functions, classes or variables in a namespace, you do it this way:
namespace foo
{
void f();
}
namespace bar
{
void f();
}
This declares two functions f in namespaces foo and bar respectively. The same you will find in header files; if there is no namespace specified as above, then the function/class/variable is in global namespace. Nothing more.
using namespace now allows you to use functions from a namespace without having to specify it explicitly:
// without:
foo::f();
bar::f();
f(); // unknown!
using namespace foo;
foo::f(); // still fine...
bar::f();
f(); // now you call foo::f
Be aware that this is bad practice, though (the link refers to namespace std, but same applies for all namespaces).
This is even worse in header files: there is no way to undo the effect of a declared using namespace <whatever> again – so you impose it on all users of your header, possibly causing great trouble to some of them. So please don't ever use it in header files.
There are three approaches I can think of right now:
Use the IDE: A modern development environment should be able (possibly with the help of plug-ins) to analyze your code while you edit, and tell you the authoritative qualified name of any identifier you hover the mouse cursor over.
Of course this is not an option if you are not using an IDE, and sometimes even IDEs may get confused and give you wrong information.
Use the compiler and guesswork: If you already have a hunch which namespace you might be in, you can define some object, reference it via qualified name, and see if the code compiles, like so:
const int Fnord = 1;
const int* Probe = &::solid::guess::Fnord;
One caveat is that it may give misleading results if using namespace or anonymous namespaces are involved.
Use the preprocessor: Most compilers define a preprocessor macro that tells you the name of the function it is used in, which may include the namespace; for example, on MSVC, __FUNCTION__ will do just this. If the file contains a function that you know will be executed, you can have that function tell you its authoritative qualified name at run-time, like so:
int SomeFunction(void)
{
printf("%s\n", __FUNCTION__);
}
If you can't use standard output, you might store the value in a variable and use a debugger to inspect it.
If you can find no such function, try defining a class with a static instance of itself, and placing the code in the constructor.
(Unfortunately I can't think of a way to inspect the macro's value at compile-time; static_assert came to my mind, but it can't be used inside functions, and __FUNCTION__ can't be used outside.)
The macro is not standardized though, and may not include the namespace (or it may not exist at all). On GCC for instance, __FUNCTION__ will only give you the unqualified name, and you will have to use __PRETTY_FUNCTION__ instead.
(As of C99 and C++11 there does exist a standardized alternative, __func__, but the format of the function name is unspecified, and may or may not include the namespace. On GCC it does not.)
I have a project in code blocks that uses many different files - quite often written by other programmers. At the moment I have a situation in which I have two different sub-projects containing function named in the same manner. Let's say: F(int x). So F(int x) is defined in two source files in two different locations and they have two different headers. Also I have created two different namespaces for those headers:
namespace NS1
{
extern "C"{
#include "header1definingF.h"
}
}
namespace NS2
{
extern "C"{
#include "header2definingF.h"
}
}
But still compiler complains that it has multiple definition of F(int x). How can I workaround this in Code::Blocks (In Visual Studio it works just fine).
EDIT: To be more clear those headers include C code. I haven't thought it will be so messy. There are like thousands of source files using other projects including thousands of functions again... so what to do. I have absolutely no idea how to make it work.
I wonder why it works on Visual Studio, but not on Code Blocks. This suggests you do have an include guard.
Does this help?
Project->Build options...->Linker settings (tab)
-Wl,--allow-multiple-definition
I can't understand your problems clearly, but i think you should understand how the compiler works, when you use gcc to compel your program, your program first will be run include operator, that means if you include a header, the compiler will copy the header file to the file. if you include the header twice there will be a twice define error.so you must guarantee once,you can use
#ifndef __FILE_NAME__
#define __FILE_NAME__
// your code
#endif
If your problem is the redefine the function, you should know how the compiler distinguish the function, i think your problem is you do not use the namespace when you use the function.
The problem is that the namespace do not work for C functions (extern "C").
Here is a simple sample which do not compile:
namespace NS1
{
extern "C"{
int f()
{
return 1;
}
}
}
namespace NS2
{
extern "C"{
int f()
{
return 2;
}
}
}
In this case the two functions are different but have the same name: f(). If you just declare the functions, it will compile but they must refer to the same function.
This second sample works fine. The functions have the name NS1::f() and NS2::f() which are differents.
namespace NS1
{
int f()
{
return 1;
}
}
namespace NS2
{
int f()
{
return 2;
}
}
If you want to use two different c code, you can use objcopy which can help you to have a NS1_f() and NS2_f() function. After that you should rename all functions of the libraries in your includes. In this case, no namespace are used. This is normal, there is no namespace in C. Equivalent functions:
int NS1_f()
{
return 1;
}
int NS2_f()
{
return 2;
}
Short of editing the .cpp files themselves and renaming the functions (which is not a practical solution), your options are either making sure to only include one of the header files with duplicate functions at a time (which could be a huge maintainance problem) or, and this would be my recommendation, make use of namespaces. They will save you a ton of hassle in this situation.
You may need one of two things. The following is called a Header Guard:
#ifndef MYHEADER_H
#define MYHEADER_H
//your header code goes here
#endif
This way the header is only included once per object file that asks for it. However, if you want to have two methods with the same identifier, they have to be part of different Namespaces:
namespace myspace1{
void func(void);
};
namespace myspace2{
void func(void);
};
Other than that, there's not really much else you can do. You shouldn't have two functions with the same name in general. Also, you would have to modify this in the header files that you mentioned.
You are allowed to declare functions as often as you want, however they can only have ONE definition.
I believe you have to edit cpp files as well to nest the two functions into a corresponding namespace. Plus, you have to choose which function you want to call like namespace::function() or you can use using namespace with either of the namespaces you created. Hope this helps!
[Updates #1] It is easier to get confused between the declaration and definition of a function. Remember that you can redeclare non-member functions. Thus, if a header file only contains non-member function declarations, it is safe to include it multiple times in one translation unit (a cpp file). Adding ifndef/define in a header file is a good habit for avoiding potential problems but that is not what resolves your problem.
Your problem is that you want to have two different function definitions with the same function signature(its name and arguments) and that's not allowed in C++. You can either change one of their signatures or put them into a different namespace (which you are trying but without touching their definitions). Both ways require you to edit files containing their definitions.
[Updates #2]
As you updated the question with that the code is in C, I've searched and found this:
What should I do if two libraries provide a function with the same name generating a conflict?
it will surely help you to understand your problem more clearly and find a solution. Good luck!
I was once told in a programming class that C++ had achieved a better readability by letting the programmer declare its variable anywhere in a function block. This way, the variables were grouped together with the section of the code that dealt with it.
Why don’t we do the same for includes?
Put differently, why is it discouraged to put the include file next to the definition that will actually use it?
parser::parser()
{
// some initialization goes there which does not make use of regex
}
#include <boost/regex.hpp>
parser::start()
{
// here we need to use boost regex to parse the document
}
One of the reasons for this is that #include are context-less, they are just plain text inclusion, and having it in the middle of the code might have some unwanted effects. Consider for example that you had a namespace, and all your code in this file belongs to the namespace:
// Include on demand:
namespace ns {
void f() {} // does not need anything
//... lots of other lines of code
#include <vector>
void g() { std::vector<int> v; }
}
Now that might even compile fine... and wrong. because the inclusion is inside a namespace, the contents of the file are dumped inside ns and the included file declares/defines ::ns::std::vector. Because it is header only it might even compile fine, only to fail when you try to use that in an interface with a different subsystem (in a different namespace) -- This can be fixed, you only need to close all contexts, add the inclusion and reopen the same contexts...
There are other situations where the code in your translation unit might actually affect the includes. Consider, for example, that you added a using namespace directive in your translation unit. Any header included after that will have the using namespace directive in place, and that might also produce unwanted effects.
It could also be more error prone in different ways. Consider two headers that defined different overloads of f for int and double. You might add one (say the int version) towards the beginning of the file and use it, then add the other and use it. Now if you call f(5.0) above the line where the second header is included, the int version will be called --only overload available to the compiler at this point--, which would be a hard to catch error. The exact same line of code would have completely different meaning in different places in your file (admittedly that is already the case, but within the declarations in your file it is easier to find which is the one being picked up and why)
In general, the includes declare elements that you will be using in your component, and having them on the top provides a list of dependencies in a quick glance.
Imagine the following file:
#include <someheader>
namespace myns {
void foo() {
}
void bar() {
// call something from someheader:
func();
}
}
It might be tempting to put #include <someheader> nearer the point of usage. That would be fine iff you wrote the following instead:
namespace myns {
void foo() {
}
}
#include <someheader>
namespace myns {
void bar() {
// call something from someheader:
func();
}
}
The problem is in a medium/large sized file it's rather easy to loose track of quite how deeply nested you are inside namespaces (and other #ifdefs), depending on your indentation style. You might come back later and decide to move things around, or add another nested namespace.
So, if you write the #include at the top always you can never get bitten by accidentally writing something like:
namespace myns {
void foo() {
}
// Whoops, this shouldn't be inside myns at all!
#include <someheader>
void bar() {
// call something from someheader:
func();
}
}
which would be somewhere between wrong and very wrong depending on what exactly is in <someheader>. (You could for example end up with UB, by violating the ODR having multiple definitions which although otherwise legal and identical sequence of tokens match different functions and so violate § 3.2.5).
It's discouraged because most programmers are used to includes at the top of the file. Force of habit I think, and for consistency with 99% of existing code.
When I personally want to see what headers are included, I only look at the top. In special (and thankfully rare) cases where something is fishy, I might look for includes in the whole file.
To the compiler it makes no difference anyway.
The following code will cause compile errors in g++4.4:
// File test.cpp
namespace A
{
#include <iostream>
}
int main()
{
return 0;
}
I have this requirement because some third party library comes without namespace protected, and if I directly include these headers, my namespace is polluted.
As a result, I tried to create namespaces for those libraries, but if the library includes some "std headers" the above approach will fail.
Can anybody help?
Thank You!
I believe 17.4.2.1 [lib.using.headers] forbids including standard library headers in a namespace :
A translation unit shall include a header only outside of any external declaration or definition, and shall
include the header lexically before the first reference to any of the entities it declares or first defines in that
translation unit.
I don't think there is anything you can do besides filing a request to the library author.
This approach will most likely lead you to trouble. You could approach the problem by manually including each such standard header before entering the namespace, and the include guards would take care of not re-including the header inside the namespace.
That would take care of your current error, but it would on the other hand break too many other things --if the library is precompiled then the symbols used in your code and the symbols in the binary library would be different symbols (libname::foo() used in your code, ::foo() defined in the binary). Even if the library is header only, any fully qualified access to the library within the library itself would break (void foo() { ::bar(); } where foo and bar are inside the library).
A valid approach that you might want to try (even if cumbersome, and requiring real work) would be writting a wrapper that is within it's own namespace, and uses the library. Then include your wrapper instead of the actual library headers.
My advice, on the other hand, would be ignoring the problem altogether. Declare your own objects within your namespaces and that would take care of the possible name collisions. As long as you keep away from using namespace statements you will be fine.
Use fully qualified names when using calls to standard libraries like std::cout instead of writing using namespace std;. This way, both can coexist.
Why do we need both using namespace and include directives in C++ programs?
For example,
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
}
Why is it not enough to just have #include <iostream> or just have using namespace std and get rid of the other?
(I am thinking of an analogy with Java, where import java.net.* will import everything from java.net, you don't need to do anything else.)
using directives and include preprocessor directives are two different things. The include roughly corresponds to the CLASSPATH environment variable of Java, or the -cp option of the java virtual machine.
What it does is making the types known to the compiler. Just including <string> for example will make you able to refer to std::string :
#include <string>
#include <iostream>
int main() {
std::cout << std::string("hello, i'm a string");
}
Now, using directives are like import in Java. They make names visible in the scope they appear in, so you don't have to fully qualify them anymore. Like in Java, names used must be known before they can be made visible:
#include <string> // CLASSPATH, or -cp
#include <iostream>
// without import in java you would have to type java.lang.String .
// note it happens that java has a special rule to import java.lang.*
// automatically. but that doesn't happen for other packages
// (java.net for example). But for simplicity, i'm just using java.lang here.
using std::string; // import java.lang.String;
using namespace std; // import java.lang.*;
int main() {
cout << string("hello, i'm a string");
}
It's bad practice to use a using directive in header files, because that means every other source file that happens to include it will see those names using unqualified name lookup. Unlike in Java, where you only make names visible to the package the import line appears in, In C++ it can affect the whole program, if they include that file directly or indirectly.
Be careful when doing it at global scope even in implementation files. Better to use them as local as possible. For namespace std, i never use that. I, and many other people, just always write std:: in front of names. But if you happen to do it, do it like this:
#include <string>
#include <iostream>
int main() {
using namespace std;
cout << string("hello, i'm a string");
}
For what namespaces are and why you need them, please read the proposal Bjarne Stroustrup gave 1993 for adding them to the upcoming C++ Standard. It's well written:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0262.pdf
In C++ the concepts are separate. This is by design and useful.
You can include things that without namespaces would be ambiguous.
With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted.
Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.
In C++ #include and using have different functions.
#include puts the text of the included file into your source file (actually translation unit), namespaces on the other hand are just a mechanism for having unique names so that different people can create a "foo" object.
This comes from C++ not having the concept of a module.
Keep in mind that namespaces in C++ are open, that means that different files can define different parts of the same namespace (sort of like .NET's partial classes).
//a.h
namespace eg {
void foo();
}
//b.h
namespace eg {
void bar();
}
The include is defining the existence of the functions.
The using is making it easier to use them.
cout as defined in iostream is actually named "std::cout".
You could avoid using the namespace by writing.
std::cout << "Hello World";
These keywords are used for different purposes.
The using keyword makes a name from a namespace available for use in the current declarative region. Its mostly for convenience so that you do not have to use the fully qualified name all the time. This page explains it in some detail.
The #include statement is a pre processor directive and it tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. That is, you can think of this statement as copying the included file into the current one. The compiler then compiles the entire file as if you wrote all the code in one big file.
As pointed out, C++ and Java are different languages, and do somewhat different things. Further, C++ is more of a 'jest grew' language, and Java more of a designed language.
While using namespace std; isn't necessarily a bad idea, using it for all namespaces will eliminate the whole benefit. Namespaces exist so that you can write modules without regard to name clashes with other modules, and using namespace this; using namespace that; can create ambiguities.
I think the other answers are missing the point slightly. In all of C++, Java and C#, the using/import thing is entirely optional. So that's not different.
And then you have to do something else to make code be visible anyway, in all three platforms.
In C++, you minimally have to include it into the current translation unit (good enough for many implementations of vector, string, etc.), often you have to add something to your linker as well, although some libraries do that automatically based on the include (e.g. boost when building on Windows).
And in C# you have to add a reference to the other assembly. That takes care of the equivalent of includes and link settings.
And in Java you have to ensure the code is on the classpath, e.g. adding the relevant jar to it.
So there are very closely analogous things required on all three platforms, and the separation between using/import (a convenience) and actual linkage resolution (a requirement) is the same in all three.
You need to understand namespaces if you want to truly understand this.
With include you are just including the header file.
With using namespace you are declaring you are using a given namespace that contains stuff such as cout. so if you do this:
using namespace std;
to you use cout you can just do
cout << "Namespaces are good Fun";
instead of:
std::cout << "Namespaces are Awesome";
Note that if you do not #include <iostream> you won't be able to use neither std::cout nor cout in your declarations and so forth because you're not including the header.
One liner (not that this is something new :)):
using std allows you to omit std:: prefix, but you cannot use cout at all without iostream.
Even Stroustrup refers to the #include mechanism as somewhat hackish. However it does make separate compilation much easier (ship compiled libraries and headers instead of all source code).
The question really is "why did C++ -- after it already had the #include mechanism -- add namespaces?"
The best example I know of about why #include isn't enough comes from Sun. Apparently Sun developers had some trouble with one of their products because they had written a mktemp() function that happened to have the same signature as a mktemp() function that was included through from a file that was itself included through a header the project actually wanted.
Of course the two functions were not compatible, and one could not be used as a substitute for the other. On the other hand, the compiler and linker did not realize this when building the binary, and sometimes mktemp() would call one function, and sometimes it would call another, based on the order different files were compiled or linked.
The problem stems from the fact that C++ was originally compatible with -- and essentially piggy-backed on top of -- C. And C has only a global namespace. C++ solved this problem -- in code that is not compatible with C -- through namespaces.
Both C# and Java (1) have a namespace mechanism (namespace in C#, package in Java), (2) are usually developed through IDEs that handle referring to binaries for the developer, and (3) don't allow freestanding functions (a class scope is something of a namespace, and reduces the risk of polluting the global namespace) so they have a different solution to this problem. However, it is still possible to have some ambiguity regarding which method you're calling (say, a name clash between two interfaces that a class inherits), and in that case all three languages require the programmer to clearly specify which method they're actually looking for, usually by prepending the parent class/interface name.
In C++, the include directive will copy and paste the header file into your source code in the preprocessing step. It should be noted that a header file generally contains functions and classes declared within a namespace. For example, the <vector> header might look similar to something like this:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
Supposing you need to define a vector in your main function, you do #include <vector> and you have the piece of code above in your code now:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
int main(){
/*you want to use vector here*/
}
Notice that in your code the vector class is still located in the std namespace. However, your main function is in the default global namespace, so simply including the header will not make the vector class visible in global namespace. You have to either use using or do prefixing like std::vector.