Question

Say I have a function

void do_something() {
    //....
    #ifdef FEATURE_X
        feature_x();
    #endif
    //....
}

I can compile and run this with no problems; if I want the feature I can pass -D FEATURE_X and it works.

However, what if I would like to put do_something into another file (And not have to recompile that file as well each time I decide to change the option). If it was in the same file, I assume that

const int FEATURE_X=0;

void do_something() {
    //....
    if(FEATURE_X) {
        feature_x();
    }
    //....
}

will use dead code elimination properly, eliminating the call. If I put this in another file, without LTO,

extern const int FEATURE_X;

void do_something() {
    //....
    if(FEATURE_X) {
        feature_x();
    }
    //....
}

It will not remove the code (It has no way of knowing). So, with link time optimization enabled, can the compiler detect the value of FEATURE_X at link time, determine if the code is used or not, and remove it if appropriate?

Was it helpful?

Solution

GCC does cross module unreachable function removal, but it will not be able to determine the code is dead in your last testcase, because the constant value of FEATURE_X will be determined too late.

If you will use -D way or put your const int FEATURE_X=0; into every module then yes, the code will be eliminated.

OTHER TIPS

If instead of the referenced code:

extern const int FEATURE_X;

void do_something() {
    //....
    if(FEATURE_X) {
        feature_x();
    }
    //....
}

what if it was done with a link time variable like so:

extern const int FEATURE_X;

void do_something() {
    //....
    if(NULL != &FEATURE_X) {
        feature_x();
    }
    //....
}

Then in the linker instruction file, define

define exported symbol FEATURE_X = 0x0

Would there be anyway to optimize it out at link time?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top