将#include包装在命名空间块中是个好主意吗? [英] Is it a good idea to wrap an #include in a namespace block?

查看:106
本文介绍了将#include包装在命名空间块中是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C头文件编译为C和C ++(它只使用来自公共子集的功能,并使用 externC) 。

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包装在命名空间块中是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆