PlatformIO Community

Debug build variable optimized by default

Heyo,

I’m having troubles using the Debugger in PIO: the variables are optimized by default.
All these tests are done on fresh new project.

example program:

int test(int a) { return a + 88; }

void loop() {
  int a = test(332);

  while (1) {
    //just blink a led
  }
}

I tested this behavior on:

  • Arduino Uno board with Arduino

[env:uno]
platform = atmelavr
board = uno
framework = arduino

  • Nucleo F446RE with framework-mbed @ ~6.51504.0

[env:nucleo_f446re]
platform = ststm32
board = nucleo_f446re
framework = mbed
platform_packages = framework-mbed @ ~6.51504.0

I tested this thread solution by adding:

build_unflags = -Os
build_flags = -O0 -g3 -ggdb

but it’s not working, the variable are optimized out. No locals in frame 0 (loop function)…

to force non optimization the only solution is to add volatile keyword, but it’s not convinient to use this method on existing programs.

I’m on win10, pio 4.3.4

Thank you for your help !

Today’s compilers no longer stick to the variable scope defined by the C/C++ standard (basically from the opening to the closing curly braces). Instead they use a smaller scope from the first to the last use of a variable. Functionally, this is equivalent. But the difference becomes apparent in the debugger.

As a result the scope of the variable a in loop() is zero. The variable has no purpose in the program and is therefore discarded by the compiler.

In order to inspect the variable, you have to do something with it, e.g.:

Serial.println(a);

Then the variable will exist and be inspectable on at least this single line.

Yay I found the solution by only adding to the platfromio.ini :smiley:

debug_build_flags = -O0 -g -ggdb


This other example given on the documentation was giving me the following error

Linking .pio\build\nucleo_f446re\firmware.elf
c:/…/.platformio/packages/toolchain-gccarmnoneeabi/bin/…/lib/gcc/arm-none-eabi/9.2.1/…/…/…/…/arm-none-eabi/bin/ld.exe:F:…pio\build\nucleo_f446re\STM32F446XE.ld.link_script.ld:1: ignoring invalid character `#’ in expression
c:/…/.platformio/packages/toolchain-gccarmnoneeabi/bin/…/lib/gcc/arm-none-eabi/9.2.1/…/…/…/…/arm-none-eabi/bin/ld.exe:F:…pio\build\nucleo_f446re\STM32F446XE.ld.link_script.ld:1: syntax error
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\nucleo_f446re\firmware.elf] Error 1