C 中的命名空间 [英] Namespaces in C

查看:25
本文介绍了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 中的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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