Search code examples
c++gccwarningswarning-level

More warnings with -Os


This program

int main()
{
    int a, b;
    a = b;
    return 0;
}

compiles without warnings or errors if you compile it with

g++ -Wall test.cpp

However, if you compile it with optimisations on, even at the same warning level

g++ -Wall -Os test.cpp

Then it will start complaining that you're using uninitialised variables!
(Note: the actual program is slightly longer and doesn't expose the problem as clearly as this little example here.)

I've tried to search with google, but either I'm not using the right search terms, or this is not a known phenomenon. Anyway, my questions basically are

  • Why would the compiler give this warning with -Os but not with -O0, even at the same warning level? (If anything, I'd expect it to be the other way around for this little example, since the variables can be optimised away entirely, and then the problem would vanish.)
  • Are there any other compiler options that trigger unexpected warnings like this? Since I'm interested in making my programs bug-free, I like to see all of them!
  • Is this a known feature? If so, where can I find it? I did try searching.
  • Or is this just a glitch in my particular version of the compiler (gcc 4.3.2-1.1, Linux, 32 bit)?

Solution

  • The compiler needs to do extra checks in order to perform some optimizations, which leads it to emit extra warnings. There is a brief explanation of it in the relevant chapter of An Introduction to GCC.

    By the way, on my platform (32 bit ubuntu 12.04 on x86) the code produces warnings with gcc 4.6.3, gcc 4.7.0 and with a gcc 4.8 snapshot:

    uninitialized.cpp: In function 'int main()': uninitialized.cpp:3:9: warning: variable 'a' set but not used [-Wunused-but-set-variable] uninitialized.cpp:4:10: warning: 'b' is used uninitialized in this function [-Wuninitialized]