PlatformIO Community

Class constructor is not called for global instances

The example below demonstrates the problem. a1 which is a static object is not initialized by the constructor (bad) while a2 is (good).

Is this expected, or a matter of a misconfigured compiler?

class A {
  public:
    A(int val): val_(val) {}
    int val_;
};

A a1(11);

void main(void) {
  A a2(22);
  printk("a1.val_=%d, a2.val_=%d\n", a1.val_, a2.val_);
}

Printed output:

a1.val_=0, a2.val_=22

My platformio.io:

[env:nrf52_dk]
platform = nordicnrf52
board = nrf52_dk
framework = zephyr
debug_tool = jlink
monitor_speed = 115200
monitor_port = COM7
debug_build_flags = -O0 -g -ggdb
build_flags =
  -I .pio/build/nrf52_dk/zephyr/include/generated
extra_scripts = extra_script.py

That’s not good at all, this indicates that there might be something wrong with the startup script or the linker script and only zeroes out the memory (as if it was .bss) but doesn’t copy the init data (.data) into RAM :confused:

Please open an issue at Issues · platformio/platform-nordicnrf52 · GitHub, this is critical…

@maxgerhardt, I added a simple variable b and it seems that the init data copy does work but that the constructor is not called. Still file a bug?

Test

class A {
  public:
    A(int val): val_(val) {}
    int val_;
};

A a1(11);
int b = 123;

void main(void) {
  A a2(22);
  printk("a1.val_=%d, a2.val_=%d, b=%d\n", a1.val_, a2.val_, b);
}

Output

a1.val_=0, a2.val_=22, b=123

Yes because that probably means that the startup script doesn’t have the code thta calls into the C++ constructors

Done. Thanks @maxgerhardt.

Just for kicks, if manually call into __libc_init_array() as the first thing in main(), does it execute? :slight_smile:

Might have to predeclare it with like extern "C" void __libc_init_array();.