How can I tell gcc not to inline a function?

2019-01-03 05:31发布

Say I have this small function in a source file

static void foo() {}

and I build an optimized version of my binary yet I don't want this function inlined (for optimization purposes). is there a macro I can add in a source code to prevent the inlining?

标签: c gcc inline
8条回答
聊天终结者
2楼-- · 2019-01-03 05:52

I work with gcc 7.2. I specifically needed a function to be non-inlined, because it had to be instantiated in a library. I tried the __attribute__((noinline)) answer, as well as the asm("") answer. Neither one solved the problem.

Finally, I figured that defining a static variable inside the function will force the compiler to allocate space for it in the static variable block, and to issue an initialization for it when the function is first called.

This is sort of a dirty trick, but it works.

查看更多
Explosion°爆炸
3楼-- · 2019-01-03 05:56

Use the noinline attribute:

int func(int arg) __attribute__((noinline))
{
}

You should probably use it both when you declare the function for external use and when you write the function.

查看更多
登录 后发表回答