当我这样定义宏时:
[niko@dev1 test]$ cat m1.c
#define FL_UINT_FLINE_(N) typedef struct fl_uint_line_## N ##e { unsigned int indexes[N]; } fl_uint_line_## N ##e_t;
FL_UINT_FLINE_(4)
FL_UINT_FLINE_(8)
int main() {
fl_uint_line_4e_t fl4;
fl_uint_line_8e_t fl8;
}
[niko@dev1 test]$
它编译完美。但是我不得不在'## N ##'之前和之后添加'e'字符('e'代表元素)因为没有'e'我会得到一个编译错误:
[niko@dev1 test]$ cat m2.c
#define FL_UINT_FLINE_(N) typedef struct fl_uint_line_## N ## { unsigned int indexes[N]; } fl_uint_line_## N ##_t;
FL_UINT_FLINE_(4)
FL_UINT_FLINE_(8)
int main() {
fl_uint_line_4_t fl4;
fl_uint_line_8_t fl8;
}
[niko@dev1 test]$ gcc -c m2.c
m2.c:1:42: error: pasting "fl_uint_line_4" and "{" does not give a valid preprocessing token
#define FL_UINT_FLINE_(N) typedef struct fl_uint_line_## N ## { unsigned int indexes[N]; } fl_uint_line_## N ##_t;
^
m2.c:2:1: note: in expansion of macro ‘FL_UINT_FLINE_’
FL_UINT_FLINE_(4)
^
m2.c:1:42: error: pasting "fl_uint_line_8" and "{" does not give a valid preprocessing token
#define FL_UINT_FLINE_(N) typedef struct fl_uint_line_## N ## { unsigned int indexes[N]; } fl_uint_line_## N ##_t;
^
m2.c:3:1: note: in expansion of macro ‘FL_UINT_FLINE_’
FL_UINT_FLINE_(8)
^
[niko@dev1 test]$
C 中宏的正确语法是什么,使我的类型定义看起来像这样: (没有“e”):
typedef struct fl_uint_line_4 {
unsigned int indexes[4];
} fl_uint_line_4_t;
typedef struct fl_uint_line_8 {
unsigned int indexes[8];
} fl_uint_line_8_t;
最佳答案
我在您的宏定义中添加了续行,以便于阅读:
#define FL_UINT_FLINE_(N) typedef struct fl_uint_line_## N ## { \
unsigned int indexes[N]; } fl_uint_line_## N ##_t;
##
运算符连接两个标记以形成一个新标记。连接标识符(N
扩展到的内容)和 {
会产生类似 foo{
的东西,这不是有效的标记。删除第二个 ##
来解决这个问题,不需要它:
#define FL_UINT_FLINE_(N) typedef struct fl_uint_line_## N { \
unsigned int indexes[N]; } fl_uint_line_## N ##_t;
关于c - C 中动态类型的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34820324/