简体   繁体   English

C语言中的宏(#define)

[英]A macros in the C language (#define)

I am reading source code of hoard memory allocator, and in the file of gnuwrapper.cpp, there is the following code 我正在阅读囤积内存分配器的源代码,并在gnuwrapper.cpp的文件中,有以下代码

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

What's the meaning of CUSTOM_PREFIX(malloc)(x) ? CUSTOM_PREFIX(malloc)(x)的含义是什么? is CUSTOM_PREFIX a function? CUSTOM_PREFIX是一个函数吗? But as a function it didn't defined anywhere. 但作为一个功能,它没有在任何地方定义。 If it's variable, then how can we use variable like var(malloc)(x) ? 如果它是变量,那么我们如何使用变量如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)

In your code, since CUSTOM_PREFIX is defined to be nothing, the string CUSTOM_PREFIX(malloc)(x) will expand to 在您的代码中,由于CUSTOM_PREFIX被定义为空,字符串CUSTOM_PREFIX(malloc)(x)将扩展为

(malloc)(x)

which is equivalent to the usual 这相当于平常

malloc(x)

However, the CUSTOM_PREFIX allows the developer to choose a different memory management function. 但是,CUSTOM_PREFIX允许开发人员选择不同的内存管理功能。 For example, if we define 例如,如果我们定义

#define CUSTOM_PREFIX(f) my_##f

then CUSTOM_PREFIX(malloc)(x) will be expanded to 那么CUSTOM_PREFIX(malloc)(x)将扩展为

my_malloc(x)

CUSTOM_PREFIX is defined as nothing, so it will just disappear, leaving behind (malloc)(x) , which is the same as malloc(x) . CUSTOM_PREFIX被定义为无,因此它将消失,留下(malloc)(x) ,这与malloc(x)相同。 Why? 为什么? I don't know. 我不知道。 Perhaps other places in the code set CUSTOM_PREFIX to something else. 也许代码中的其他地方将CUSTOM_PREFIX设置为其他内容。

At a guess, its a macro which changes calls to malloc(x) etc. into something like: 猜测,它是一个宏,它将对malloc(x)等的调用更改为:

DEBUG_malloc( x );

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. 您可以选择自己提供宏,为函数提供自定义前缀,或者不在何种情况下不更改名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM