即使在命名空间之间,包含保护也应该是唯一的吗?
我在两个命名空间(例如 A 和 B)中使用相同的类名。在声明具有不同命名空间的类时,包含保护是否应该是唯一的?
我的意思是不能有两个文件名 AFile.h (在不同的目录中)具有相同的包含防护并声明不同的名称空间吗?
//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
I am using same class name in two namespaces, say A and B. Should the include guards be unique while declaring the classes with different 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果某些代码(直接或间接)需要同时查看 A::CAFile 和 B::CAfile,则您的警卫需要有所不同。
包含防护由预处理器处理,预处理器完全不了解类(更不用说名称空间)。如果在处理 C++ 文件时包含这两个文件,并且它们具有相同的标头保护,则只有其中一个声明将保留在编译器将看到的预处理源中。
看看诸如 Boost 文件之类的东西,它们对标头防护有一些约定(如果我没记错的话)。
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).
包含防护仅影响预处理器,而预处理器不了解 C++,并且完全忽略命名空间。因此,守卫对于文件来说应该是唯一的,而不是对于命名空间来说是唯一的。
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.
简而言之,这可能是个好主意。以下是 GCC 的做法...
我不知道如何使用名称空间,但包含保护对于您的打包接口应该是唯一的(可以全部位于一个名称空间内或分布在多个名称空间中)。
In short, it's probably a good idea. Here is how the GCC does their's...
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).
就我个人而言,我一直在使用
#pragma Once
,因为我关心的编译器支持它,并且您可以避免此处提到的那种问题。如果你想使用#include 守卫,那么你可能需要巧妙地处理它。否则,#include
ingFoo/header.h
可能无法工作,因为您已经#include
dBar/header.h
>。在其他情况下,我不同意样式指南,但 Google 建议 <代码><项目>_<路径>_<文件>_H_。尽管这确实意味着如果您将文件复制到不同的路径,则必须更新
#include
防护。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
ingFoo/header.h
may not work because you already#include
dBar/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.