Should the include guards be unique even between namespaces?
I am using same class name in two namespaces, say A and B. Should the include guards be unique while declaring the classes with diffe开发者_运维技巧rent namespaces too?
I mean can't there be two files names AFile.h (in different directories) with same include guards and declaring different namespaces?
//File 1:
#ifndef AFILE_H
#define AFILE_H
namespace A {
class CAFile {...
};
};
#endif
//File 2:
#ifndef AFILE_H
#define AFILE_H
namespace B {
class CAFile {...
};
};
#endif
Your guards need to be different if some code (directly or indirectly) needs to see both A::CAFile and B::CAfile.
The include guards are dealt with by the preprocessor, that has no knowledge at all of classes (let alone namespaces). If both these files are included when processing a c++ file, and they have the same header guards, only one of the declarations will remain in the preprocessed source that the compiler will see.
Look at things like Boost files, they have some conventions for the header guards (if I remember correctly).
Include guards only affect the preprocessor and the preprocessor doesn't know C++ and completely ignores namespaces. So guards should be unique to a file, not to a namespace.
In short, it's probably a good idea. Here is how the GCC does their's...
#ifndef _GLIBCXX_VECTOR
#define _GLIBCXX_VECTOR 1
I don't know about using a namespace per say but the include guard should be unique to your packaged interface (which could all be within one namespace or spread across many).
Personally, I've been using #pragma once
because it's supported on the compilers I care about and you can avoid the kind of problems you mention here. If you want to use #include
guards, then you may need to be clever about it. Otherwise #include
ing Foo/header.h
may not work because you already #include
d Bar/header.h
.
I don't agree with the style guide in other cases, but Google recommends <PROJECT>_<PATH>_<FILE>_H_
. Although that does mean that if you copy files around to different paths you're going to have to update the #include
guard.
精彩评论