开发者

A macros in the C language (#define)

开发者 https://www.devze.com 2022-12-31 12:15 出处:网络
I am reading source code of hoard memory allocator, and in the file of gnuwrapper.cpp, there is the following code

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)


In your code, since CUSTOM_PREFIX is defined to be nothing, the string CUSTOM_PREFIX(malloc)(x) will expand to

(malloc)(x)

which is equivalent to the usual

malloc(x)

However, the CUSTOM_PREFIX allows the developer to choose a different memory management function. For example, if we define

#define CUSTOM_PREFIX(f) my_##f

then CUSTOM_PREFIX(malloc)(x) will be expanded to

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). Why? I don't know. Perhaps other places in the code set CUSTOM_PREFIX to something else.


At a guess, its a macro which changes calls to malloc(x) etc. into something like:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号