C macros (#define)

I am reading the source code of the drive's memory allocator, and the following code is in the gnuwrapper.cpp file

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

What is the value of CUSTOM_PREFIX(malloc)(x) ? is there a CUSTOM_PREFIX function? But as a function, it was not defined anywhere. If a variable, then how can we use a variable of type 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 a variable, so if it doesn't define, then define here. #define CUSTOM_PREFIX #endif #define CUSTOM_MALLOC(x) CUSTOM_PREFIX(malloc)(x) ===> what 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) 
+4
source share
3 answers

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

 (malloc)(x) 

which is equivalent to ordinary

 malloc(x) 

However, CUSTOM_PREFIX allows the developer to select 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) 
+6
source

CUSTOM_PREFIX defined as nothing, so it just disappears, leaving (malloc)(x) , which is the same as malloc(x) . What for? I dont know. Perhaps there is something else elsewhere in the CUSTOM_PREFIX code.

0
source

Under the assumption, this is a macro that changes calls to malloc (x), etc. into something like:

 DEBUG_malloc( x ); 

You can choose a macro yourself, provide an individual prefix for functions or not, in which case the names will not be changed.

0
source

Source: https://habr.com/ru/post/1310593/


All Articles