【发布时间】:2014-01-16 23:30:33
【问题描述】:
有没有一种方法可以让宏使用传递给它的定义值,而不是定义文本本身?
这是一个奇怪的例子,我预计预处理器可以实现。
一个名为test.c 的C 文件,其中包含两次以定义从main 调用的两个不同函数。
#ifndef IS_INDIRECT
#define IS_INDIRECT
/* int */
#define NUMTYPE int
#define PREFIX int_
#include "test.c"
#undef NUMTYPE
#undef PREFIX
/* short */
#define NUMTYPE float
#define PREFIX float_
#include "test.c"
#undef NUMTYPE
#undef PREFIX
#include <stdio.h>
int main(int argc, const char **argv)
{
printf("test int %d\n", int_squared(4));
printf("test float %f\n", float_squared(2.5));
return 0;
}
#else
/* function body */
#define fn(prefix, id) prefix ## id
NUMTYPE fn(PREFIX, squared)(NUMTYPE val)
{
return val * val;
}
#endif
给出以下错误:
In file included from test.c:18:0:
test.c:37:12: error: conflicting types for 'PREFIXsquared'
NUMTYPE fn(PREFIX, squared)(NUMTYPE val)
^
test.c:35:24: note: in definition of macro 'fn'
#define fn(prefix, id) prefix ## id
^
In file included from test.c:9:0:
test.c:37:12: note: previous definition of 'PREFIXsquared' was here
NUMTYPE fn(PREFIX, squared)(NUMTYPE val)
^
test.c:35:24: note: in definition of macro 'fn'
#define fn(prefix, id) prefix ## id
我想让宏扩展 PREFIX 到它定义的值,所以我得到 int_squared 而不是 PREFIXsquared
【问题讨论】:
标签: c c-preprocessor