Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling the order of static objects' constructor

I'm writing a tiny kernel with c++11 and have two instances with the same type which have to be constructed before any other static objects are created.

The code I wrote is as follows:

// test.hpp
class test {
  // blahblah...
};

// test.cpp
typedef char fake_inst[sizeof(test)] __attribute__((aligned(alignof(test))));

fake_inst inst1;
fake_inst inst2;

// main.cpp
extern test inst1;
extern test inst2;

int kmain() {
    // copy data section

    // initialize bss section

    new (&inst1) test();
    new (&inst2) test();

    // call constructors in .init_array

    // kernel stuffs
}

It builds and works as expected without no warning messages, but not with LTO.

I get tons of warning messages complaining the type matching and I wonder if there's a workaround since it confuses me to find the other 'real' warning or error messages.

Any suggestion?

like image 654
Inbae Jeong Avatar asked Mar 17 '12 06:03

Inbae Jeong


People also ask

Which constructor is called first in C# static or default?

That's why you can see in the output that Static Constructor is called first. Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.

Can we modify static variable in constructor?

If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

What is the construction order of global variables?

Global variables within each translation unit are constructed in order of their declaration. The order between translation units is, indeed, not specified. They're not even required to be "constructed" (dynamically initialized) before entering main , see [basic. start.

Are static variables initialized before constructor?

All static members are always initialized before any class constructor is being called.


1 Answers

Could you use GCC's init_priority attribute?

Some_Class  A  __attribute__ ((init_priority (2000)));
Some_Class  B  __attribute__ ((init_priority (543)));

http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html#C_002b_002b-Attributes

like image 102
Pubby Avatar answered Oct 25 '22 15:10

Pubby