0

I ported my code from stm32f072 to stm32f105. Since then I have an issue with global variables, it seems they don't get initialized. I use Atollic TrueStudio and their compile and build tools. For the new platform I tried converting the existing "eclipse" project and also to create a new one from CubeMx.

I got a Hardfault when accessing a global object. The "workaround" was moving the new statement in the accessing function. The debugger showed that even when having the new statement the global var was 0x00.

I also use an std::queue which has an size() of 0xffffffe7 when not inserted anything yet, which let me believe this also comes from a missing initialization.

I want to solve the issue, not move all init in the beginning of the main function as a workaround.

My code looks something like this:

#include <queue>

std::queue<Telegram> telegram_in_fifo;
Port *port1 = new IoPort(/* some args */);

void some_function() { // tried calling from Interrupt or from main 
    // port1 is 0x00 here
    port1 = new IoPort(/* some args */);
    // now port1 has proper address and accessing internal data works without hardfaults

    uint64_t size = telegram_in_fifo.size(); // this is 0xffffffe7
    if(size <= fifo_max) {
        telegram_in_fifo.push(telegram);
    }
}
Fritz
  • 831
  • 7
  • 23
  • Where are you calling `some_function` from? This might be a case of *static initialisation order fiasco*. – john Dec 27 '20 at 14:26
  • 2
    My crystal ball tells me that `some_function()` is called from an initializer of some global variable in a different source file. The order of initialization of global variables from different source files is unspecified. – Igor Tandetnik Dec 27 '20 at 14:26
  • please try to prepare a [mcve]. With the code you posted alone it isnt possible to get a size of `0xffffffe7` for the queue – 463035818_is_not_an_ai Dec 27 '20 at 14:27
  • some_function is called in an Interrupt or from main – Fritz Dec 27 '20 at 14:28
  • @Fritz Might the interrupt be called before main? – john Dec 27 '20 at 14:28
  • Have a look at this: https://stackoverflow.com/questions/43650493/understanding-c-runtime-environment-arm-where-to-start It's likely that the C Runtime is not initializing your variables, probably due to a toolchain mismatch or some other tools issue. Go through your build environment with a tine toothed comb to look for inconsistencies. – Tumbleweed53 Dec 27 '20 at 14:29
  • @john no, since I enable the interrupt in main and send explicitly later. I now have to investigate further about the static init order fiasco – Fritz Dec 27 '20 at 14:31
  • @Fritz The better technique is to use a lazy evaluated [_Singleton_](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern) class, which contains all the necessary `static` variables as encapsulated class member variables (non static). – πάντα ῥεῖ Dec 27 '20 at 14:34

0 Answers0