[ACCEPTED]-Should I include header file within a namespace?-namespaces
You SHOULD NOT place #include
directives inside 23 your own namespace. What you have done 22 is to place all of the contents of unistd.h
inside 21 your namespace as well; thus what used to 20 be (and should remain!) ::close()
is now declared 19 as MyAddedNameSpace::close()
. This is NOT what you want.
Your "solution" of 18 adding the line #include <unistd.h>
at the top of your .cpp 17 file fixes the problem, but only for this 16 one .cpp file. What you've done is included 15 the library header the correct way (without 14 your namespace), and then when your header 13 (a.h) is included, it does #include <unistd.h>
again (this 12 time within your namespace), but this time the include guards 11 in that file prevent it from being processed 10 again. So for this .cpp file you're OK, but 9 any other file that does #include <a.h>
will have the 8 same problem that you originally had.
There 7 may be some rare occasion where you have 6 a good reason for using #include
within your own 5 namespace, but you will most likely be including 4 one of your own headers (or some other file) - NOT 3 a library header! - and even then, it's 2 probably not the ideal solution.
In a.h
#include <unistd.h>
namespace MyAddedNameSpace {
struct File
{
void func(int fd);
};
}
In 1 a.cpp
#include "a.h"
namespace MyAddedNameSpace {
void File::func(int fd)
{
::close( fd );
}
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.