Can a gcc program detect when link time optimization (-flto) is enabled?

473 Views Asked by At

I have some code that MUST have link time optimization enabled to work correctly. I need constant expression evaluation of:

  extern const char[] PROGMEM constantTable = {1,2,3,4,5};
    :
   char x = constantTable[4];

(PROGMEM is an avr-gcc construct that puts the constant in a separate memory section that is subsequently loaded into flash rather than ram, and at execution time will need special care to access. But not at compile time...)

Is there some way that I can detect at compile time (or link time) that -flto has NOT been specified, so that I can issue an error message?

I have already compared the pre-defined symbols with and without -flto using the "-dM -E" trick, and there don't seem to be any differences. Any idea for other tricks?

(should __builtin_constant_p() be "evaluated" at link time for -flto? It isn't as of gcc 5.4.0 (latest "vendor supported" avr compiler.))

1

There are 1 best solutions below

0
On

One way is to try to test an external global variable for an impossible value:

// foo.c
const int LTO_in_use = 1;

and

// bar.c
#include <stdio.h>
extern int LTO_in_use;
void LTO_Not_Enabled(void) __attribute__ (( error("") ));

int main() {
    if (LTO_in_use == 99) {
        LTO_Not_Enabled();
    }
}

Any global variable will work, as long as you know an impossible value. If you do create a specifc new variable, it should never actually end up referenced in the runtime, so it will get GC'ed by lto anyway.