What is the most general approach to place a struc

2019-07-18 19:37发布

问题:

I am working on an embedded C project using GCC for ARM V-4.8.3 toolchain. I have an array of look-up structures that are read only during the life cycle of the entire program. Since I am running out of RAM (and have plenty of Flash unused) it is better idea to push them into the flash, which will not affect the function of the program. The problem is how.

One way to do so is using the variable __attribute__ ((section ("TEXT"))) provided by GCC. In this case my code is compiler dependent. If I want to use my code using Microchip compiler for instance I need to edit the code to port to the new environment.

The other way coming to my mind is using the linker script. The structure is only declared into the code.

It seems to me that the second approach is a bit more portable. Although it is still needed to adjust the linker script, to me it is better. Is there more general approach that would make the code more portable into the context of placing variables into the flash?

Qualifying them as a constant, means that they will be placed into rodata section. Not into the text section where they "belong".

回答1:

If it doesn't matter where in the flash they end up, simply declaring the struct as static const should be sufficient and 100% portable.

__attribute__ and other non-standard things should only be needed when you need to allocate something at a specific address.



回答2:

You have to look at your specific compiler/linker to determine how to place it into flash.
Sometimes const will work sometimes it will place it still into RAM.
static const is portable, but it can't guarantee the placement into flash.

That's because Ansi-C doesn't know anything about flash or RAM.

There are even systems, where you have to use pragmas to place into flash.

#pragma define_section myFlash_table ".calibTable.text" RW
#pragma section myFlash_table begin
...
#pragma section myFlash_table end

A portable version should use consts, but you have to remember that it isn't bullet proof.