Is it a good idea to wrap an #include in a namespace block?(将#include 包装在命名空间块中是个好主意吗?)
问题描述
我有一个 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.
这篇关于将#include 包装在命名空间块中是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将#include 包装在命名空间块中是个好主意吗?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
