Methods to Preserve Variables in Keil, IAR, and CubeIDE
1 Introduction
Sometimes, our applications require variables to maintain continuity or to preserve the state, for example, during Bootloader jumps or resets where certain critical variables should not be initialized. Different compilation environments have different settings. This article summarizes this operation and introduces the methods used in Keil, IAR, and CubeIDE. The chip used in this article is STM32G431RBT6.2 Method to Prevent Variable Initialization in IARThe implementation in IAR is relatively simple; you can directly use the keyword “__no_init” to modify the variable:To verify successful execution, you can periodically reset the system and observe the variable changes. For example, the following sample program resets the system periodically, and you will find that the data of Test_NoInit increases by 10 based on the previous data, rather than being initialized and then increasing by 10.3 Method to Prevent Variable Initialization in KeilKeil does not have a keyword like IAR’s, and there are version differences. Below are the introductions for each:To prevent uninitialized variables from being set to 0, you must place them in a special section that satisfies the ZI data segment (.bss), which has the UNINIT attribute.3.1 Operation of ArmĀ® Compiler 5Modify the project’s linker file, *.sct file, as shown in the image below:Here, the RAM is divided into two regions, where RW_IRAM2 is the area for uninitialized variables, with the attribute UNINIT, defining a region named NO_INIT.Define variables in this section, and AC5 must use the zero_init modifier.3.2 Operation of ArmĀ® Compiler 6In AC6, you need to add the .bss ZI definition, as shown in the modified sct file:Define variables in the section part. AC5 and AC6 also have differences; zero_init is no longer supported as a modifier, as shown in the definition below:For the specific differences between versions AC5 and AC6, you can refer to the descriptions in the Keil help files:4 Method to Prevent Variable Initialization in CubeIDEThe implementation in CubeIDE is similar to that in Keil, requiring modification of the linker file *.ld. First, divide the RAM to create an uninitialized RAM area:Add area descriptions and include the area name:Define variables in this uninitialized area:Additionally, it is worth noting that some STM32 series have specific option configuration bits regarding whether certain RAM areas will be initialized after a reset. For example, in the STM32L4 series, to prevent SRAM2 variables from being initialized, you need to configure the SRAM2_RST bit in the option byte, as shown in the image below:[Paid] Graduation Project Resource Package