有没有办法(Ab)使用C预处理器在C中模拟命名空间
我是这样想的:
#define NAMESPACE name_of_ns
some_function() {
some_other_function();
}
这将被转换为:
name_of_ns_some_function() {
name_of_ns_some_other_function();
}
发布于 2008-12-23 21:44:08
在使用名称空间前缀时,我通常会为缩写名称添加宏,这些宏可以在包含头部之前通过#define NAMESPACE_SHORT_NAMES
激活。标题foobar.h可能如下所示:
// 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
如果我想在包含文件中使用短名称,我会这样做
#define FOOBAR_SHORT_NAMES
#include "foobar.h"
我发现这比使用Vinko Vrsalovic (在注释中)所描述的名称空间宏更干净、更有用。
发布于 2008-12-23 20:15:41
另一种选择是声明一个结构来保存所有函数,然后静态地定义函数。然后,您只需担心全局名称结构的名称冲突。
// foo.h
#ifndef FOO_H
#define FOO_H
typedef struct {
int (* const bar)(int, char *);
void (* const baz)(void);
} namespace_struct;
extern namespace_struct const foo;
#endif // FOO_H
// foo.c
#include "foo.h"
static int my_bar(int a, char * s) { /* ... */ }
static void my_baz(void) { /* ... */ }
namespace_struct const foo = { my_bar, my_baz }
// main.c
#include <stdio.h>
#include "foo.h"
int main(void) {
foo.baz();
printf("%d", foo.bar(3, "hello"));
return 0;
}
在上面的例子中,my_bar
和my_baz
不能直接从main.c调用,只能通过foo
调用。
如果您有一组声明具有相同签名的函数的名称空间,那么您可以为该集合标准化您的名称空间结构,并选择在运行时使用哪个名称空间。
// goo.h
#ifndef GOO_H
#define GOO_H
#include "foo.h"
extern namespace_struct const goo;
#endif // GOO_H
// goo.c
#include "goo.h"
static int my_bar(int a, char * s) { /* ... */ }
static void my_baz(void) { /* ... */ }
namespace_struct const goo = { my_bar, my_baz };
// other_main.c
#include <stdio.h>
#include "foo.h"
#include "goo.h"
int main(int argc, char** argv) {
namespace_struct const * const xoo = (argc > 1 ? foo : goo);
xoo->baz();
printf("%d", xoo->bar(3, "hello"));
return 0;
}
my_bar
和my_baz
的多个定义并不冲突,因为它们是静态定义的,但是底层函数仍然可以通过适当的名称空间结构访问。
发布于 2008-12-23 19:32:24
您可以使用##运算符:
#define FUN_NAME(namespace,name) namespace ## name
并将函数声明为:
void FUN_NAME(MyNamespace,HelloWorld)()
不过看起来挺尴尬的。
https://stackoverflow.com/questions/389827
复制相似问题