[riot-devel] RIOT and static initializers in C++

Pekka Nikander pekka.nikander at iki.fi
Fri Sep 19 18:56:53 CEST 2014

>> static initializers don’t seem to work on RIOT. Setting a breakpoint in the constructor reveals, that it is never called. I believe the static initialization should occur before calling main. If I am not mistaken, RIOT calls the function startup before the main.
>> Usually the compiler should take care of the initialization. Does someone know why this initialization does not happen on RIOT? 

As a reference point, at Ell-i we explicitly decided *not* to support run-time-initialised static constructors.  That is, we *do* support compile-time-initialised static constructor, but made the linker to explicitly barf if there are any run-time-initialised static constructors.  The main reason for that is just a matter of taste:  personally, I think that performing initialisations at runtime is a waste of flash memory, and therefore initialisations should be performed at compile time, if only possible.  With C++11, it is usually possible to write compile-time initialised static constructors, if you are careful and design the data structures correctly.

But YVVM, and I do understand if RIoT wants to decide in some other way.

That said, in the Ell-i linker script we use the following to barf on run-time static initialisers:

   __ctor_begin = .;
   KEEP (*crtbegin.o(.ctors))       /* The initial dummy, empty entry */
   KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))
   KEEP (*(SORT(.ctors.*)))
   KEEP (*crtend.o(.ctors))         /* The last NULL entry */
   __ctor_end = .;

   ASSERT(__ctor_begin == __ctor_end, "C++ static constructors are not supported.");

If you do want to support run-time static constructors, here is a piece of example code to be called from somewhere before main:

extern void (*__ctor_begin)(void);
extern void (*__ctor_end)(void);

for (void (*ctor)(void) = __ctor_begin; ctor != __ctor_end; ctor++)

I haven't tested that, it may or may not work.  In the linker script, you have to have the same lines as above, without the ASSERT(...).

--Pekka Nikander

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4827 bytes
Desc: not available
URL: <http://lists.riot-os.org/pipermail/devel/attachments/20140919/0661c1cf/attachment.bin>

More information about the devel mailing list