php 如何宏定义,PHP 源码碎片 - 从 _emalloc 的宏定义看同名函数与宏

文件位置:Zend/zend_alloc.h# define _emalloc(size) \

(__builtin_constant_p(size) ? \

ZEND_ALLOCATOR(size) \

: \

_emalloc(size) \

)__builtin_constant_p 是编译器gcc内置函数,用于判断一个值是否为编译时常量,如果是常数,函数返回1 ,否则返回0。

看似很诡异,怎么循环嵌套这个宏的定义了呢?实际这里是有一个和_emalloc宏同名的函数

文件位置:Zend/zend_alloc.cZEND_API void* ZEND_FASTCALL _emalloc(size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)

{

//...

}

上面ZEND_FILE_LINE_DC和ZEND_FILE_LINE_ORIG_DC debug 调试使用,非 debug 模式为空。

demo 1#include

void _emalloc(int size)

{

printf("function %d\n",size);

}

# define ZEND_ALLOCATOR(size) printf("ZEND_ALLOCATOR %d\n",size)

# define _emalloc(size) \

(__builtin_constant_p(size) ? \

ZEND_ALLOCATOR(size) \

: \

_emalloc(size) \

)

int main(int argc, char const *argv[])

{

_emalloc(12);

int a = 2;

_emalloc(a);

return 0;

}

运行输出结果与预期相符ZEND_ALLOCATOR 12

function 2

demo 2#include

void _emalloc(int size);

# define ZEND_ALLOCATOR(size) printf("ZEND_ALLOCATOR %d\n",size)

# define _emalloc(size) \

(__builtin_constant_p(size) ? \

ZEND_ALLOCATOR(size) \

: \

_emalloc(size) \

)

int main(int argc, char const *argv[])

{

_emalloc(12);

int a = 2;

_emalloc(a);

return 0;

}

void _emalloc(int size)

{

printf("function %d\n",size);

}

无法运行

119c33267f9687c2efc6129cdcb2eb56.png

总结

编译通过的前提:同名函数在同名宏前面定义,否则宏无法正确展开。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值