CubeMX, OpenStm32 project with main.cpp with statically allocated objects results in linker error for _sbrk etc.
I’m using CubeMX to generate an OpenStm32 project and then convert the project to C++ with a main.cpp file. All works well until I add a statically-allocated object in the scope of a function i.e., something like this:
static MyClass myObj();
}This results in linker errors (can’t find sbrk and a bunch of other functions). The solution is to add a g++ compiler option of
This is added in eclipse by going to project properties, tree C/C++ Build / Settings, Tool Settings tab, tree MCU G++ Compiler / Miscellaneous, and in field Other Flags, add -fno-threadsafe-statics.
Why -fno-threadsafe-statics works:
A static allocation in file scope is not an issue but a static allocation in function scope will result in calls to __cxa_guard_acquire and __cxa_guard_release. This gcc.godbolt.org example shows side-by-side C++ & assembly with calls to the ‘guard’ calls. This
suggests using -fno-threadsafe-statics. This
describes why these guards might be needed. And this example using -fno-threadsafe-statics
shows how the ‘guard’ calls are elliminated (works in OpenStm32 too).