Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with global-constructor warning in clang?

Tags:

c++

clang

Clang warns (when using -Weverything or Wglobal-constructors) about constructors for static objects.

warning: declaration requires a global constructor
      [-Wglobal-constructors]
A A::my_A; // triggers said warning
     ^~~~

Why is this relevant and how should one deal with this warning?

Simple example code:

class A {
  // ...
  static A my_A;
  A();
};

A A::my_A; // triggers said warning
like image 326
Walter Avatar asked Mar 29 '13 17:03

Walter


3 Answers

Here is a simpler case that triggers the same warning:

class A {
public:
  // ...
  A();
};

A my_A; // triggers said warning


test.cpp:7:3: warning: declaration requires a global constructor [-Wglobal-constructors]
A my_A; // triggers said warning
  ^~~~
1 warning generated.

This is perfectly legal and safe C++.

However for every non-trivial global constructor you have, launch time of your application suffers. The warning is simply a way of letting you know about this potential performance problem.

You can disable the warning with -Wno-global-constructors. Or you can change to a lazy initialization scheme like this:

A&
my_A()
{
    static A a;
    return a;
}

which avoids the issue entirely (and suppresses the warning).

like image 69
Howard Hinnant Avatar answered Oct 15 '22 06:10

Howard Hinnant


Solution from @Howard Hinnant avoid global constructor, but it do exit time destructor still. It can be found with option -Wexit-time-destructors

So Ideal solution can be based on CR_DEFINE_STATIC_LOCAL from http://src.chromium.org/svn/trunk/src/base/basictypes.h

A& my_A()
{
    static A &a = *new A;
    return a;
}
like image 28
Maxim Kholyavkin Avatar answered Oct 15 '22 06:10

Maxim Kholyavkin


If you can declare the constructor constexpr, that will suppress the warning (because this guarantees constant initialization). See https://godbolt.org/z/s3hY83jdr

like image 41
David Stone Avatar answered Oct 15 '22 04:10

David Stone