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?
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.
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.
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.
All static members are always initialized before any class constructor is being called.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With