将#include 包装在命名空间块中是个好主意吗?

2022-01-14 00:00:00 namespaces include c++

我有一个 C 头文件,它被编写为同时编译为 C 和 C++(它只使用公共子集中的功能,并使用 extern "C" 东西).

I have a C header that was written to compile as both C and C++ (it only uses features from the common subset, and uses that extern "C" thing).

问题是,该标头在全局命名空间中声明了一些东西.出于通常的原因,我宁愿避免这种情况.我想过这样做:

Problem is, that header declares stuff in the global namespace. I'd rather avoid that for the usual reasons. I thought about doing this:

namespace foo {
#include <foo.h>
}

这样做是个好主意吗?我有不包括编辑头文件的替代方法吗?

Is doing this a good idea? Do I have alternatives that don't include editing the header file?

推荐答案

不,这是个坏主意.使用 C++ 声明,可能会引入链接器错误,因为标识符在错误的命名空间中声明.使用 C 声明,它可以工作,但它可能会隐藏全局命名空间中标识符之间的冲突(我猜你试图避免这种冲突),直到链接时间;它并没有真的将标识符放在命名空间中.

No, it’s a bad idea. With C++ declarations, it's likely to introduce linker errors as identifiers get declared in the wrong namespace. With C declarations, it works, but it may hide clashes between identifiers in the global namespace (which you were trying to avoid, I guess) until link time; it doesn't really put the identifiers in a namespace.

更好的办法是将您自己的标识符放在命名空间中,避免在全局名称中定义除 main 之外的任何内容.

A better idea would be to put your own identifiers in a namespace and avoid defining anything but main in the global one.

相关文章