12.5 Locating a Constant at a Specific Address in Program Memory [DD]

In this example, the constant table is located at a specific address in program memory. When a constant is specifically placed at an address in program memory, it must be placed in its own PSV section using the space(psv) attribute. If a device has only one PSV page (16K instruction words or less), the (psv) section and (auto_psv) section will share the same PSV page by default.

Note:
  1. It is not possible to place a constant at a specific address in Program Memory using the space(auto_psv) attribute. Only the space(psv) attribute may be used to perform this task.
  2. On dsPIC33A devices, only the address() attribute is used, and the address must be divisible by 4. Helper functions are not required.

The __builtin_tbladdress() helper function can be used to find the address of a constant stored in program memory. The __psv__ access qualifier is used to specify compiler-managed access.

#include "stdio.h"
#include "xc.h"

__psv__ const unsigned __attribute__ ((space(psv), address (0x2000))) table[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

int main(void)
{
  unsigned sum=0, u;
  long addr;

  /* compute the address of table and print it */
  addr = __builtin_tbladdress(table);

  /* print the address of table */
  printf ("table[] is stored at address 0x%lx\n", addr);

  /* sum the values in table[] */
  for (u=0; u<10; u++) {
       sum += table[u];
  }

  /* print the sum */
  printf ("sum is %d\n", sum);
}

The equivalent constant definition for the array table in assembly language appears below. The .align directive is optional and represents the default alignment in program memory. Use of * as a section name causes the assembler to generate a unique name based on the source file name.

        .section *,address(0x2000),psv
        .global _table
        .align 2
_table:
        .word 0,1,2,3,4,5,6,7,8,9

In order to allocate table in data memory, the space(psv) attribute could be changed to space(data). In this case, the specified address would be a data memory address. In the absence of a space attribute, the keyword const directs the C compiler to allocate the variable in the same space as other compiler constants. Constants are allocated in program memory by default, or in data memory if the constants-in-data memory model is selected.