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 包装在命名空间块中是个好主意吗?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01