C语言中的宏(#define)
我正在阅读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)
I am reading source code of hoard memory allocator, and in the file of gnuwrapper.cpp, there is the following code
#define CUSTOM_MALLOC(x) CUSTOM_PREFIX(malloc)(x)
What's the meaning of CUSTOM_PREFIX(malloc)(x)
? is CUSTOM_PREFIX
a function? But as a function it didn't defined anywhere. If it's variable, then how can we use variable like var(malloc)(x)
?
More code:
#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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的代码中,由于 CUSTOM_PREFIX 被定义为空,因此字符串
CUSTOM_PREFIX(malloc)(x)
将扩展为与通常等效的字符串
。但是,CUSTOM_PREFIX 允许开发人员选择不同的内存管理功能。例如,如果我们定义
CUSTOM_PREFIX(malloc)(x)
将扩展为In your code, since CUSTOM_PREFIX is defined to be nothing, the string
CUSTOM_PREFIX(malloc)(x)
will expand towhich is equivalent to the usual
However, the CUSTOM_PREFIX allows the developer to choose a different memory management function. For example, if we define
then
CUSTOM_PREFIX(malloc)(x)
will be expanded toCUSTOM_PREFIX
被定义为空,因此它会消失,留下(malloc)(x)
,与malloc(x)
相同>。为什么?我不知道。也许代码中的其他位置将CUSTOM_PREFIX
设置为其他内容。CUSTOM_PREFIX
is defined as nothing, so it will just disappear, leaving behind(malloc)(x)
, which is the same asmalloc(x)
. Why? I don't know. Perhaps other places in the code setCUSTOM_PREFIX
to something else.据猜测,它是一个宏,它将对 malloc(x) 等的调用更改为类似以下内容:
您可以选择自己提供宏,为函数提供自定义前缀,或者不提供,在这种情况下,名称将不会被改变了。
At a guess, its a macro which changes calls to malloc(x) etc. into something like:
You can choose to supply the macro yourself, to provide a customised prefix for the functions, or not in which case the names won't be changed.