Add a section for version number

I want to add a "section" to the arduino project to save version information.

I want to access this information from the .elf file.

As an example, below is an example I made in another C project.

main.c
...
#define BUILD_VERSION_INFO "ver*1.46"
__attribute__((section("versionInfo"))) const char MY_VERSION[] = BUILD_VERSION_INFO;
...

Then, I can read the "versionInfo" section information with readelf.exe.

command line => readelf.exe main.elf -p versionInfo

As I mentioned above, I want to do the same in the Arduino project.
But my attempts were unsuccessful.

Does anyone know how I can do it?

First step: You need to tell the compiler that it's not allowed to optimize out the variable if it's unused. Use e.g. the [[gnu::used]] attribute.
If you want to be able to access the variable in other source files, you also need to mark it extern (constants have internal linkage by default in C++).

#define BUILD_VERSION_INFO "ver*1.46"
extern const char MY_VERSION[] [[gnu::used,gnu::section("versionInfo")]] = BUILD_VERSION_INFO;

Second: You need to stop the linker from throwing away your unused section. Either remove the --gc-sections flag in ~/.arduino15/packages/arduino/hardware/avr/1.8.6/platform.txt, or add -Wl,--undefined=MY_VERSION.

compiler.c.elf.flags=[...] -Wl,--gc-sections,--undefined=MY_VERSION

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.