为什么GCC保持空函数? [英] Why does GCC keep empty functions?

查看:336
本文介绍了为什么GCC保持空函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,如果我想创建C中的可选功能,我只需创建两个函数是这样的:

In most cases if I want to create an optional feature in C, I simply create two functions like this:

#ifdef OPTIONAL_SOMETHING
void do_something(int n, const char *s)
{
    while (n--) {
        printf("%s", s);
    }

    /* ...You might get the point, really do something... */
}
#else
void do_something(int n, const char *s)
{
    /* Empty body */
}
#endif

因此​​,如果符号是不确定的 - 当功能被禁用 - 一个空函数被编译成可执行文件

So if the symbol is undefined — when the feature is disabled — an empty function is compiled into the executable.

钻研组装上市,似乎GCC的编译和电话的空函数时,在优化是禁用。如果在启用优化,也与 -O2 -O3 ,它的只编译必要的协议栈处理的code,但它优化了调用指令。总而言之,它保持功能。

Delving into the assembly listing, it seems that GCC compiles and calls the empty functions when the optimizations are disabled. If the optimizations are enabled, also with -O2 and -O3, it compiles only the necessary stack handling code, but it optimizes out the call instructions. All in all it keeps the function.

关于同样适用于非空,但不使用的方法。

About the same applies for the non-empty, but unused methods.

这应该简单地抛出了整个事情,但事实并非如此。为什么它是默认的行为?而刚刚出于好奇:我怎样才能消除呢?

It should simply throw out the whole thing, but it does not. Why it is the default behavior? And just for curiosity: How I can eliminate this?

推荐答案

由于函数有外部链接,(是不是静态),编译器不能消除它,因为另一个对象文件可能引用它。如果函数静态,它会被完全消除。

Since the function has external linkage (is not static), the compiler cannot eliminate it because another object file might reference it. If the function is static, it will be eliminated completely.

这篇关于为什么GCC保持空函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆