Does the compiler take care the useless codes like

2019-06-24 08:39发布

问题:

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.