cancel
Showing results for 
Search instead for 
Did you mean: 

The mysterious __libc_init_array() in Cube IDE - is it only for C++ ??

PHolt.1
Senior II

Supposedly this is only used by C++ but see various threads e.g.

https://www.eevblog.com/forum/microcontrollers/a-question-on-gcc-ld-linker-script-syntax/msg4754165/#msg4754165

https://www.eevblog.com/forum/microcontrollers/how-do-i-enable-link-section-overlap/msg3715957/#msg3715957

https://www.eevblog.com/forum/microcontrollers/mcu-programming-101-writeup/msg5402906/#msg5402906

https://www.eevblog.com/forum/microcontrollers/is-st-cube-ide-a-piece-of-buggy-***/msg5403485/#msg5403485

If you google it, you find a disturbing number of suggestions (nothing concrete!) that in the STM environment, Cube IDE, this function is not only for C++ constructors etc but is also used to initialise some statics in libc.a functions. One suggestion was that malloc() does not work without it. ST does not distribute sources to libc.a although some people on eevblog located probable sources for newlib (dated 1990, IIRC). Much of libc.a is also not re-entrant and needs to be mutexed in any RTOS environment.

Does anyone know the real answer?

21 REPLIES 21
PHolt.1
Senior II

The whole reason for me starting this thread was to chase down the multiple statements on the internet - going back years, and in many places - that __libc_init_array() is only for C++, while a few others contradicted this assertion but never giving any detail.

It has been achieved 😀

That's a good link Jan posted, but IIRC it contains some errors e.g.

Because Newlib is a static library with a separate object file for every function, all you need to do to replace a function is define it in your program. The linker won’t go looking for it in static libraries if it finds it in your code.

is not true in the ST context; you cannot replace a function in libc.a (or any .a file) unless that function is "weak", and ST compiled entire libc.a as non-weak. I did replace stuff like printf() (posted extensively on eevblog) and used one of the GCC tools to weaken the whole libc.a to enable replacement.

Only stuff in .o files can be replaced with own-provided functions.

IMHO, anyone expecting printf() to work without first initialising a UART is going to get into big trouble.

Q: if you wanted to initialise a UART, how would you arrange it so that calling __libc_init_array() does it? Presumably you need to list the functions which need calling, somewhere.

PHolt.1
Senior II

See here for details

https://tinyurl.com/25je6rpt

URL shortened because this forum doesn't like a substring in the EEVBLOG URL 😁