Namespaces in C(C 中的命名空间)
问题描述
有没有办法(ab)使用 C 预处理器来模拟 C 中的命名空间?
Is there a way to (ab)use the C preprocessor to emulate namespaces in C?
我的想法是这样的:
#define NAMESPACE name_of_ns
some_function() {
some_other_function();
}
这将被翻译成:
name_of_ns_some_function() {
name_of_ns_some_other_function();
}
推荐答案
当使用命名空间前缀时,我通常为缩短的名称添加宏,可以在包含标题之前通过 #define NAMESPACE_SHORT_NAMES
激活.标头 foobar.h 可能如下所示:
When using namespace prefixes, I normally add macros for the shortened names which can be activated via #define NAMESPACE_SHORT_NAMES
before inclusion of the header. A header foobar.h might look like this:
// inclusion guard
#ifndef FOOBAR_H_
#define FOOBAR_H_
// long names
void foobar_some_func(int);
void foobar_other_func();
// short names
#ifdef FOOBAR_SHORT_NAMES
#define some_func(...) foobar_some_func(__VA_ARGS__)
#define other_func(...) foobar_other_func(__VA_ARGS__)
#endif
#endif
如果我想在包含文件中使用短名称,我会这样做
If I want to use short names in an including file, I'll do
#define FOOBAR_SHORT_NAMES
#include "foobar.h"
我发现这是一个比使用 Vinko Vrsalovic 描述的命名空间宏(在评论中)更清洁、更有用的解决方案.
I find this a cleaner and more useful solution than using namespace macros as described by Vinko Vrsalovic (in the comments).
这篇关于C 中的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C 中的命名空间


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