15.4 Changing the Default Function Allocation

Cases may arise when a specific function must be located at a specific address, or within some range of addresses. The easiest way to accomplish this is by using the address attribute, described in section Function Specifiers. For example, to locate function PrintString at address 0x8000 in program memory:

int __attribute__ ((address(0x8000))) PrintString (const char *s);

Another way to locate code is by placing the function into a user-defined section, and specifying the starting address of that section in a custom linker script. This is done as follows:

  1. Modify the code declaration in the C source to specify a user-defined section.
  2. Add the user-defined section to a custom linker script file to specify the starting address of the section.

For example, to locate the function PrintString at address 0x8000 in program memory, first declare the function as follows in the C source:

int __attribute__((__section__(".myTextSection")))

PrintString(const char *s);

The section attribute specifies that the function should be placed in a section named .myTextSection, rather than the default .text section. It does not specify where the user-defined section is to be located. That must be done in a custom linker script, as follows. Using the device-specific linker script as a base, add the following section definition:

.myTextSection 0x8000 :
  {
         *(.myTextSection);
  } >program

This specifies that the output file should contain a section named .myTextSection starting at location 0x8000 and containing all input sections named .myTextSection. Since, in this example, there is a single function PrintString in that section, then the function will be located at address 0x8000 in program memory.