1

Possible Duplicate:
Is it a good idea to wrap an #include in a namespace block?

// Method One
#ifndef XXX_H
#define XXX_H
#include <iostream>
#include "myhead.h"
namespace XXX
{
    /...
}
#endif

OR

// Method Two
namespace XXX
{
#ifndef XXX_H
#define XXX_H

    #include <iostream>
    #include "myhead.h"
    /...
#endif
}

When we define a new namespace XXX, should we move #include directive inside namespace or not?

Thank you

Community
  • 1
  • 1
q0987
  • 34,938
  • 69
  • 242
  • 387

4 Answers4

6

You must not include <iostream> inside your namespace. You will get linker errors.

I would not suggest including any headers within a namespace.

The only exception would be where you have a header which defines only extern "C" functions (and no C++ functions or classes), you can usually include that in a namespace without causing linker problems. But it is still probably not a good idea.

Ben
  • 34,935
  • 6
  • 74
  • 113
  • It won't cause missing definition linker errors, but it can easily cause duplicate definition linker errors, since it's not really putting the definitions in a namespace. – R. Martinho Fernandes Mar 29 '12 at 16:42
2

It depends on what you want, as both are not equivalent. Each of them mean different thing.

If you include them inside a namespace, then the heades will expand inside the namespace, which means all the names from the header will be declared/defined inside the namespace which in your case is XXX.

So if you want that, you can do that. If you don't want that, then obviously you should not do that.

Note that if you include then inside a namespace, you may get linker errors, for those symbols which you've defined in .cpp file, but no inside XXX namespace. So the declarations will be in namesapce XXX::ABC, whereas the definitions will be in a namespace ABC. So because of this reason, you will get linker errors for symbols from <iostream> if you include this in XXX namespace.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

No, you should do your #includes outside the namespace. Otherwise you're going to mangle the names of everything in the header files you're including. In the case you've posted above you're going to mangle the names of standard library elements; it's unlikely that will even build successfully.

phooky
  • 288
  • 1
  • 6
0

Afaik .. the first one is better coding practice.. Again thats only me ..

Anerudhan Gopal
  • 379
  • 4
  • 13
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – tune2fs Nov 15 '12 at 05:52
  • @tune2fs: disagree: it *is* and answer, just not a very well backed up or useful one. – Mac Nov 15 '12 at 05:58