c - C 中动态类型的宏

标签 c

当我这样定义宏时:

    [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/

相关文章:

c - 子 pthread 发生段错误

c - 从类型 'char[128]' 分配给类型 'char *' 时的类型不兼容

c - libcurl c/c++ Kerberos 身份验证

c - 为什么 pthread_equal 是线程安全的?

c - 为什么在替换旧库时不能减小结构的大小?

C - 将数组中的 char 字符串排序为等于 char 用户输入

c - 通过在未初始化的数据段 (bss) 中打印 "garbage values",我们可以映射出先前程序中的所有值

c - 我正在做一个项目,我是使用 XOR 进行密码分析的新手。我如何使用密码分析来获取明文?

c - 如何在 c 中生成 NaN float ?

c - 两个相似的 for 循环给出不同的结果