C语言中的宏定义(#define)

4

我正在阅读Hoard内存分配器的源代码,在gnuwrapper.cpp文件中,有以下代码:

#define CUSTOM_MALLOC(x)     CUSTOM_PREFIX(malloc)(x)  

"

CUSTOM_PREFIX(malloc)(x) 的意思是什么? CUSTOM_PREFIX 是一个函数吗?但作为一个函数,它没有被定义在任何地方。如果它是变量,那么我们怎么使用像var(malloc)(x)这样的变量呢?

更多代码:

"
#ifndef __GNUC__
#error "This file requires the GNU compiler."
#endif

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>


#ifndef CUSTOM_PREFIX   ==> here looks like it's a variable, so if it doesn't define, then define here.
#define CUSTOM_PREFIX
#endif

#define CUSTOM_MALLOC(x)     CUSTOM_PREFIX(malloc)(x)    ===> what's the meaning of this?
#define CUSTOM_FREE(x)       CUSTOM_PREFIX(free)(x)
#define CUSTOM_REALLOC(x,y)  CUSTOM_PREFIX(realloc)(x,y)
#define CUSTOM_MEMALIGN(x,y) CUSTOM_PREFIX(memalign)(x,y)

如果您使用文本输入区域上方的1010按钮格式化代码,则尖括号将在代码和文本中正确显示。 - anon
非常感谢Neil。stackoverflow非常酷,有很多人愿意帮助他人,我的问题很快就得到了回答,太棒了。 - Daniel
3个回答

6

在您的代码中,由于CUSTOM_PREFIX被定义为空,字符串CUSTOM_PREFIX(malloc)(x)将展开为

(malloc)(x)

这相当于通常的

malloc(x)

然而,CUSTOM_PREFIX允许开发者选择不同的内存管理函数。例如,如果我们定义:
#define CUSTOM_PREFIX(f) my_##f

那么CUSTOM_PREFIX(malloc)(x)将被扩展为

my_malloc(x)

3
实际上,(malloc)(x)malloc(x) 不等价:前者保证是一个函数调用,而后者可能是一个宏调用(参见 C99 7.1.4 §5,其中展示了调用标准库函数的不同方式)。 - Christoph

0
猜测一下,这是一个宏,可以将对malloc(x)等的调用更改为类似以下内容的东西:
DEBUG_malloc( x );

您可以选择自己提供宏,为函数提供自定义前缀,或者不提供,在这种情况下名称将不会更改。


0

CUSTOM_PREFIX 被定义为空,因此它将消失,留下 (malloc)(x),这与 malloc(x) 相同。为什么?我不知道。也许代码中的其他地方将 CUSTOM_PREFIX 设置为其他值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接