【发布时间】:2017-09-27 11:53:47
【问题描述】:
这或多或少是要求澄清 Casting a function pointer to another type 带有示例代码
struct my_struct;
void my_callback_function(struct my_struct* arg);
void do_stuff(void (*cb)(void*));
static void my_callback_helper(void* pv)
{
my_callback_function(pv);
}
int main()
{
do_stuff(&my_callback_helper);
}
答案说“好的”编译器应该能够优化
my_callback_helper() 函数,但我在 https://gcc.godbolt.org 找不到编译器
这样做了,即使它是just a jump to my_callback_function() (-O3),也会始终生成帮助函数:
my_callback_helper:
jmp my_callback_function
main:
subq $8, %rsp
movl $my_callback_helper, %edi
call do_stuff
xorl %eax, %eax
addq $8, %rsp
ret
所以我的问题是:标准中是否有任何内容阻止编译器消除助手?
【问题讨论】:
-
根据我的经验,编译器在内联函数指针调用方面往往做得很差,即使函数指针的值可以在编译时确定。您可以尝试输入
inline关键字。据我所知,标准中没有任何内容阻止优化。
标签: c callback language-lawyer function-pointers