http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58193

            Bug ID: 58193
           Summary: init_priority attribute doesn't work on non-class
                    types
           Product: gcc
           Version: 4.8.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: wielkiegie at gmail dot com

__attribute__ ((init_priority (x))) makes it possible to order the
initialization of global objects. However, gcc rejects this attribute on
globals of non-class (or struct) types. It is still possible for gcc to emit a
constructor in .init_array section when non-class global is initialized by a
function, but it's not possible to set priority of such initializer.

$ cat i1.cpp
extern int bar();

const int foo __attribute__ ((init_priority (1000))) = bar();
$ g++ i1.cpp -c
i1.cpp:3:52: error: can only use ‘init_priority’ attribute on file-scope
definitions of objects of class type
 const int foo __attribute__ ((init_priority (1000))) = bar();
                                                    ^
$

The workaround for such a case is to wrap the type in struct.

$ cat i2.cpp
template <typename Type>
class WrapInStruct {
public:
  WrapInStruct() : _value() {}
  WrapInStruct(const Type& value) : _value(value) {}

  operator Type() const { return _value; }

private:
  Type _value;
};

extern int bar();

const WrapInStruct<int> foo __attribute__ ((init_priority (1000))) = bar();
$ g++ i2.cpp -c
$

Reply via email to