Home > other >  Optimization flag removing undefined reference to extern variable
Optimization flag removing undefined reference to extern variable

Time:01-27

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 ?

CodePudding user response:

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.

  • Related