Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言中的宏(#define)_C_Macros_C Preprocessor - Fatal编程技术网

C语言中的宏(#define)

C语言中的宏(#define),c,macros,c-preprocessor,C,Macros,C Preprocessor,我正在阅读囤积内存分配器的源代码,在gnuwrapper.cpp文件中,有以下代码 #define CUSTOM_MALLOC(x) CUSTOM_PREFIX(malloc)(x) 自定义前缀(malloc)(x)的含义是什么?自定义前缀是函数吗?但作为一个函数,它没有在任何地方定义。如果它是变量,那么我们如何使用变量,比如var(malloc)(x) 更多代码: #ifndef __GNUC__ #error "This file requires the GNU compil

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

#define CUSTOM_MALLOC(x)     CUSTOM_PREFIX(malloc)(x)  
自定义前缀(malloc)(x)
的含义是什么?
自定义前缀是函数吗?但作为一个函数,它没有在任何地方定义。如果它是变量,那么我们如何使用变量,比如
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)
\ifndef\uu GNUC__
#错误“此文件需要GNU编译器。”
#恩迪夫
#包括
#包括
#包括
#包括
#ifndef CUSTOM_PREFIX==>这里看起来像是一个变量,所以如果它没有定义,那么在这里定义。
#定义自定义前缀
#恩迪夫
#定义自定义\u MALLOC(x)自定义\u前缀(MALLOC)(x)==>这是什么意思?
#定义自定义前缀(自由)(x)自定义前缀(自由)(x)
#定义自定义_REALLOC(x,y)自定义_前缀(REALLOC)(x,y)
#定义自定义_MEMALIGN(x,y)自定义_前缀(MEMALIGN)(x,y)

在代码中,由于自定义前缀定义为“无”,字符串
自定义前缀(malloc)(x)
将扩展为

(malloc)(x)
这相当于通常的情况

malloc(x)
但是,自定义_前缀允许开发人员选择不同的内存管理功能。例如,如果我们定义

#define CUSTOM_PREFIX(f) my_##f
然后,
自定义前缀(malloc)(x)
将扩展为

my_malloc(x)

CUSTOM\u前缀
被定义为无,因此它将消失,留下
(malloc)(x)
,这与
malloc(x)
相同。为什么?我不知道。可能代码集中的其他地方将自定义前缀改为其他地方。

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

DEBUG_malloc( x );

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

如果您使用文本输入区域上方的1010按钮格式化代码,则尖括号将在代码和文本中显示得很好。非常感谢Neil。stackoverflow很酷,很多人都愿意帮助别人,我的问题在几分钟内就得到了回答,这真是太神奇了。实际上,
(malloc)(x)
并不等同于
malloc(x)
:前者保证是函数调用,而后者可能是宏调用(参见C99 7.1.4§5,了解调用标准库函数的不同方法示例)