Currently I am working on a c framework and I want to embed a c++ package into it. However, there are lots of naming conflicts occurs. So I decided to to add a namespace to the C++ source. Now the question is should I move the #include "header.h" within namespace { } block? I just spent some time to figure out a bug which was resulted from the following codes.
Original C++ source
In a.h
#include <unistd.h>
struct File
{
void func(int fd);
};
In a.cpp
#include "a.h"
void File::func(int fd)
{
::close( fd );
}
And I added the namespace like this
New a.h
namespace MyAddedNameSpace
{
#include <unistd.h>
struct File
{
void func(int fd);
};
}
New a.cpp
#include "a.h"
namespace MyAddedNameSpace
{
void File::func(int fd)
{
::close( fd );
}
}
And compiler complains that ::close() has not been declared.
The reason Why I put the #include directive inside namespace block is because the c++ package I imported also use #ifndef flag to include header files as follows. So I think the easy way is to put all codes within namespace block {}
#ifndef
#include <header1.h>
#include <header2.h>
...
#else
#include <header3.h>
#include <header4.h>
...
#endif
Now I solved this problem by adding the extra line in cpp file
#include <unistd.h> //new added line
#include "a.h"
namespace MyNameSpace
{
void File::func(int fd)
{
::close( fd );
}
}
But I am not satisfied with this solution since unistd.h header has already been included in a.h, but inside the namespace MyAddedNameSpace, or should I added the prefix MyNameSpace to all the function calls where the compiler complain no such function declared ?
Thanks for the reply.
#include <unistd.h>for your case. It's clear that,<unistd.h>is not visible toa.cpp.