简体   繁体   中英

Optimization flag removing undefined reference to extern variable

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM