declaring constant data
Martin Sebor
msebor@gmail.com
Fri Oct 8 23:18:35 GMT 2021
On 10/8/21 1:55 PM, Rafał Pietrak via Gcc-help wrote:
> Hi everybody,
>
> I'm writing code for embedded ARM microcontroler using arm-none-eabi-gcc
> version 8.3.1 20190703. I'd like to put my static data structure into
> FLASH memory to save precious RAM. My code is like this:
> ---------------------------------
> static const char *test_a[] /* __attribute__((section (".rodata"))) */ = {
> "test1",
> "test2",
> };
> static const char *test_b[] /* __attribute__((section (".rodata"))) */ = {
> "test3",
> "test4",
> };
> static const char *test_c[] /* __attribute__((section (".rodata"))) */ = {
> "test5",
> "test6",
> };
> static const struct dict_ports_s {
> const char **alias;
> const char len;
> const char *name;
> } ports[] = {
> { .name = "test0", .len = sizeof(test_a), .alias = test_a },
> { .name = "test1", .len = sizeof(test_b), .alias = test_b },
> { .name = "test2", .len = sizeof(test_c), .alias = test_c },
> };
>
> int main(int ac, char *av[]) {
> int i;
> for (i = 0; i < 3; i++) {
> printf("%d %s\n", ports[i].len , ports[i].alias[0]);
> }
> return 0;
> }
> ------------------------------------------------
>
> but neither the "const" words in declarations, nor the explicit
> selection of ".RODATA" section make those constant data structure go
> into read-only data section. Assembler, that gcc produces with "-S"
> option looks like this:
> -----------------------------------------
> .section .data.test_a,"aw"
> .align 2
> .set .LANCHOR0,. + 0
> .type test_a, %object
> .size test_a, 8
> test_a:
> .word .LC5
> .word .LC6
> .section .data.test_b,"aw"
> .align 2
> .set .LANCHOR1,. + 0
> .type test_b, %object
> .size test_b, 8
> test_b:
> .word .LC3
> .word .LC4
> .section .data.test_c,"aw"
> .align 2
> .set .LANCHOR2,. + 0
> .type test_c, %object
> .size test_c, 8
> test_c:
> .word .LC1
> .word .LC2
> ----------------------------------------------------
>
> so the structures are emitted into relevant ".data.test*" sections which
> are writable. And that's not what I need.
>
> How do I get them emitted into "a" section (with no "w" attribute)?
Try throwing a few more consts at it ;-) This:
static const char *test_a[] = { ... };
defines test_a[] to be a modifiable array of pointers to const char.
If you want the array itself to be read-only you need to declare it
const as well:
static const char* const test_a[] = { ... };
Martin
>
> BR.
>
> Rafał
> PS: I'm not a subscriber of the list, so pls Cc: responses to me directly.
>
More information about the Gcc-help
mailing list