用C命名空间 [英] Namespaces in C

查看:171
本文介绍了用C命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种办法(AB)使用 C preprocessor模仿命名空间中的 C

我沿着这些路线思考的东西:

 的#define NAMESPACE name_of_ns
some_function(){
    some_other_function();
}

这将得到翻译为:

  name_of_ns_some_function(){
    name_of_ns_some_other_function();
}


解决方案

在使用的命名空间prefixes,我通常会添加一些宏可通过的#define NAMESPACE_SHORT_NAMES 列入头之前。一个头foobar.h中可能是这样的:

  //纳入后卫
的#ifndef FOOBAR_H_
#定义FOOBAR_H_//长的名字
无效foobar_some_func(INT);
无效foobar_other_func();//短名称
#IFDEF FOOBAR_SHORT_NAMES
#定义some_func(...)foobar_some_func(__ VA_ARGS__)
#定义other_func(...)foobar_other_func(__ VA_ARGS__)
#万一#万一

如果我想在一个包括文件使用短的名字,我会做

 的#define FOOBAR_SHORT_NAMES
#包括foobar.h中

我觉得这比使用命名空间的宏由Vinko Vrsalovic描述(在评论)一个更清洁,更有效的解决方案。

Is there a way to (ab)use the C preprocessor to emulate namespaces in C?

I'm thinking something along these lines:

#define NAMESPACE name_of_ns
some_function() {
    some_other_function();
}

This would get translated to:

name_of_ns_some_function() {
    name_of_ns_some_other_function();
}

解决方案

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"

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天全站免登陆