2

Considering the following piece of code :

extern int var;

void foo(int & param)
{
   (void) param;
}

int main(void)
{
   foo(*(&var));
   return 0;
}

Compiled this way :

$ g++ -Os -o test.o -c test.cpp
$ g++ test.o

But when I remove the -Os flag, there is an undefined reference to var.

What kind of optimization are enabled by -Os to skip this undefined reference ? (I tried to replace the flag by all the optimizations it enable according to the GCC documentation but I can't reproduce without -Os.

Another question, when I compile the sample in one go :

$ g++ -c test.c

There is no error even though there is no optimization flag, why ?

  • `-Os` probably removes all of the code as it does nothing. You can output an assembly file to check that. – NathanOliver Jan 26 '23 at 16:18
  • Also note that just enabling the same flags doesn't actually enable optimization: https://stackoverflow.com/questions/53175916/g-o1-is-not-equal-to-o0-with-all-related-optimization-flags/53175963#53175963 – NathanOliver Jan 26 '23 at 16:19

1 Answers1

4

After performing some binary search on the flags, the relevant one appears to be -fipa-pure-const, demo here. The description is "Discover which functions are pure or constant. Enabled by default at -O1 and higher.", which presumably includes noticing that foo doesn't actually do anything with param.

Nathan Pierson
  • 5,461
  • 1
  • 12
  • 30