You cannot do it at compile time, but at runtime you can check whether your program optimised or not.
Write a code that definitely will be changes by optimiser, like mixing non-volatile variable with setjmp
/longjmp
, and by the value of that variable you will know whether your program is optimised or not.
#include <setjmp.h>
#include <stdio.h>
int is_optimised(void) {
int i = 1;
jmp_buf jmp_loc;
if (setjmp(jmp_loc)) {
return i; // optimiser changes it to "return 1"
}
i = 0;
longjmp(jmp_loc, 1);
return 0;
}
int main(int argc, char *argv[]) {
printf("%soptimised\n", is_optimised() ? "" : "non-");
return 0;
}
If compiled with GCC without -O
switch it prints "non-optimised
", for switches -O1
to -O4
it prints "optimised
".
Of course your mileage (with other compilers) may vary.