Does the compiler take care the useless codes like if(0)?

烈酒焚心 提交于 2020-01-03 15:59:03

问题


Recently, I am compiling the ffmpeg codes under windows use the VS2010 with intel compiler. For the following codes:

void ff_dcadsp_init(DCADSPContext *s)
{
    s->lfe_fir = dca_lfe_fir_c;
    if (ARCH_ARM) ff_dcadsp_init_arm(s);
}

the macro ARCH_ARM is defined as 0.

When I compile it under linux, there is no function in ff_dcadsp_init_arm() in the object file, while it does under windows? So I want to make sure if the compiler will do something about the useless codes and how to set it for INTEL compiler.


回答1:


Usually, most compilers are capable of taking care of that kind of the dead code, effectively removing that particular instruction / block. However, AFAIK it is not guaranteed and may differ between compilers and / or supplied optimization level settings.

However, if you want this to be handled in the preprocessing state itself (should be a better approach, IMHO, as ARCH_ARM is a MACRO), you can make use of #if preprocessor statements, to remove the dependency on compiler optimization level.

For example, in general

void ff_dcadsp_init(DCADSPContext *s)
{
    //something common code

    #if ARCH_ARM                 //this {#if...#endif} block 
        ff_dcadsp_init_arm(s);   //only get compiled if ARCH_ARM evaluates to non-zero
    #endif

   //something more common code
}



回答2:


If ARCH_ARM is a macro, you'd probably be better off with something like:

void ff_dcadsp_init(DCADSPContext *s)
{
    s->lfe_fir = dca_lfe_fir_c;
    #if ARCH_ARM != 0
        ff_dcadsp_init_arm(s);
    #endif
}

Then you don't have to concern yourself with what an optimiser will do. The C standard itself doesn't mandate that "dead" code is removed, this is totally down to how each implementation wants to do it.

The use of standard C functionality like #if is mandated by the standard, and therefore much more portable.



来源:https://stackoverflow.com/questions/30703896/does-the-compiler-take-care-the-useless-codes-like-if0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!