cancel
Showing results for 
Search instead for 
Did you mean: 

C++ constructor of static objects not called

Gustav Andersson
Associate II
Posted on February 08, 2017 at 14:18

Hello,

I am trying to use C++ in the SPC560Bxx mcu using SPC5 Studio and the free gcc vle toolchain (4.9.2).

However, it looks like constructors aren't called as I expected.

In the following example, I expect to end up in the first case of the if statement, but I end up in the else case.

class Foo {
public:
 int val;
 Foo() {
 val = 42;
 }
 void do_something() {
 if (val == 42) {
 printf('I expect to end up here');
 } else {
 printf('But I end up here');
 }
 }
};
static Foo myObject; // this ought to call the Foo's constructor

int main(void) {
 ...
 myObject.do_something();�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?
 ...
}�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?

From what I understand this is because the crt0.s doesn'tinitialize the static objects on startup.

Does anyone have a solution to my problem or aworking c++ example they can share?

#spc560b54l5 #c++11 #c++ #gcc
2 REPLIES 2
Gustav Andersson
Associate II
Posted on February 10, 2017 at 08:08

To answer my own question, I found out that if I left the .ctors section during linking and then called each constructor, my problem seems to be solved.

I had to add the following in the ld-script:

 /* .ctors are used for c++ constructors */
 .ctors :
 {
 PROVIDE(__ctors_start__ = .);
 KEEP(*(SORT(.ctors.*)))
 KEEP(*(.ctors))
 PROVIDE(__ctors_end__ = .);
 } >flash
�?�?�?�?�?�?�?�?

and then using the following __late_init function, which is called before main():

void __late_init() {
 extern void (*__ctors_start__[])(void) __attribute__((weak));
 extern void (*__ctors_end__[])(void) __attribute__((weak));
 int count = __ctors_end__ - __ctors_start__;
 int i;
 for (i = 0; i < count; i++) {
 __ctors_start__[i]();
 }
}
�?�?�?�?�?�?�?�?�?�?

Note that this only solves the construction of global objects.

Posted on February 10, 2017 at 09:40

Hello Gustav ,

I have tried yesterday to port a C Test Application on C++ Test Application in SPC5Studio

SPC560Dxx OS-Less Test Application for Discovery

Compilation is ok but i have a coredump on clock init.

i had forgotten to update my linker file.

Anyway, i will reactive a change request to create a C++ Test Application from SPC5Studio.

I will take some time.

Do not hesitate to contribute on this subject on

  Best regards

         Erwan