[cfe-dev] -Wglobal-constructors vs static initialization

Nico Weber thakis at chromium.org
Mon Dec 5 13:29:13 PST 2011


On Mon, Dec 5, 2011 at 1:27 PM, Eli Friedman <eli.friedman at gmail.com> wrote:
> On Mon, Dec 5, 2011 at 1:15 PM, Nico Weber <thakis at chromium.org> wrote:
>> Hi,
>>
>> -Wglobal-constructors looks like a very useful warning for finding
>> static initializers. However, it looks like it warns in several cases
>> where clang is smart enough to not emit a static initializer (but gcc
>> isn't, at least the versions I'm using):
>>
>> $ cat test.cc
>> #include <limits>
>>
>> class A {
>>  public:
>>  A(int n) : a_(n) {}
>>  int a_;
>> };
>>
>> int g_n = std::numeric_limits<int>::max();
>> A g_a(5);  // gcc 4.2 gets this right, 4.4 doesn't
>>
>> int main() {
>>  return g_a.a_ + g_n;
>> }
>> #include <string.h>
>> int f(char* f) {
>>  return strlen(f) == 0;
>> }
>> $ g++ -o foo test.cc -O2
>> $ otool -l foo | grep -C 5 __mod_init_func  | grep size
>>      size 0x0000000000000008
>> $ third_party/llvm-build/Release+Asserts/bin/clang++ -o foo test.cc -O2
>> $ otool -l foo | grep -C 5 __mod_init_func  | grep size
>> # Note: No output.
>>
>>
>> But:
>>
>> $ third_party/llvm-build/Release+Asserts/bin/clang++ -o foo test.cc
>> -O2 -Wglobal-constructors
>> test.cc:9:5: warning: declaration requires a global constructor
>> [-Wglobal-constructors]
>> int g_n = std::numeric_limits<int>::max();
>>    ^     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>> test.cc:10:3: warning: declaration requires a global constructor
>> [-Wglobal-constructors]
>> A g_a(5);
>>  ^~~~~~
>> 2 warnings generated.
>>
>>
>> Is this intentional, or should -Wglobal-constructors be changed to
>> only warn about constructors that do create static initializers at
>> -O2?
>
> This is mostly intentional; we don't want this warning to randomly
> appear/disappear if we change the optimizer.  (With C++11, appropriate
> constexpr markings will suppress this warning in the given cases.)

That's what I thought. Thanks!

Nico




More information about the cfe-dev mailing list