Search code examples
gccembeddedelf

How do I assign a pointer to a custom section that is added after compilation with GCC?


I'm using GCC and writing embedded software for STM32.

How do I read a section that is added with --add-section?

I want to add a section into an elf and inside my program assign a pointer to point to data of this section.

For example:

extern char * ptr_to_my_section = &my_array;

Then I will compile a file my_data.cpp and inject it into a specific section my_section.

my_data.cpp

char my_array[] = "This is the custom data";

And finally I'll create the binary executable.


Solution

  • Then I will compile a file my_data.cpp and inject it into a specific section my_section.

    You don't need to use objcopy --add-section for this. You can simply ask GCC to put your array into my_section using __attribute__((section("my_section"))).

    To find the start of this section, you can use {__start,__end} symbols which the linker "magically" adds for you:

    const char *ptr_to_my_section = &__start_my_section;
    const char *end_my_section = &__stop_my_section;