C宏函数定义语法问题

C Macros function definition syntax question

我一直在查看一个名为 hickit 的程序,有一次(count.c,函数从第 105 行开始),他们调用了一个宏函数(kavl_insert ) 来自 Klib 库,如下所示:

static void hk_count_nei2_core(int32_t n_pairs, struct cnt_nei2_aux *a, int r1, int r2)
{
    struct cnt_nei2_aux *root = 0;
    int32_t i, j, left;
    unsigned cl;
    left = 0;
    kavl_insert(nei2, &root, &a[0], 0);
...

查看Klib库(更具体地说,在kavl.h中),这个函数(我认为)定义如下:

#define __KAVL_INSERT(suf, __scope, __type, __head, __cmp) \
    __scope __type *kavl_insert_##suf(__type **root_, __type *x, unsigned *cnt_) { \

稍后在 kavl.h 文件中有这个独立的行(第 322 行):

#define kavl_insert(suf, proot, x, cnt) kavl_insert_##suf(proot, x, cnt)

我对 C 的技术知识不多(只是学习了相关的部分),我想知道它是如何工作的。大小写不同,#define 行中有“__”前导。这是如何工作的?

第一个__KAVL_INSERT宏用于声明以相同前缀(kavl_insert_)开头并以指定后缀(参数suf)结尾的函数。

所以,当你看到这个时:

__KAVL_INSERT(foo, static, int, null, null)

预处理器会将其替换为具有适当名称、作用域和参数类型的函数:

static int *kavl_insert_foo(int **root_, int *x, unsigned *cnt_) { \
    /* actual function body ... */ \
    /* with lots of trailing backshashes ... */ \
    /* because it's the only way to create ... */ \
    /* a multiline macro in C */ \
}

小写 kavl_insert 宏,另一方面:

kavl_insert(foo, &something, &whatever, 0);

只是扩展为实际的函数调用,即相当于调用上面定义的函数:

kavl_insert_foo(&something, &whatever, 0);

这种宏背后的想法通常是使用预处理器在 C 中创建通用 type-safe 数据结构,例如各种通用数据结构的 klib 库。