16.2 Runtime Startup and Initialization

A C program requires certain objects to be initialized and the processor to be in a particular state before it can begin execution of its function main(). It is the job of the runtime startup code to perform these tasks, specifically (and in no particular order):

  • Initialization of global variables assigned a value when defined
  • Initialization of the stack
  • Clearing of non-initialized global variables
  • General setup of registers or processor state

Two C run-time startup modules are included in the libc99-pic30-elf.a archive/library. The entry point for both startup modules is __reset. The linker scripts construct a GOTO __reset instruction at location 0 in program memory, which transfers control upon device Reset.

The primary startup module is linked by default and performs the following:

  1. The Stack Pointer (W15) and Stack Pointer Limit register (SPLIM) are initialized, using values provided by the linker or a custom linker script (see the 7.3 Stack section for more information).
  2. If a .const section is defined, it is mapped into the Program Space Visibility (PSV) window by initializing the PSV page and CORCON registers, as appropriate, if const-in-code memory mode is used or variables have been explicitly allocated to space(auto_psv).
  3. The data initialization template is read, causing all uninitialized objects to be cleared and all initialized objects to be initialized with values read from program memory. The data initialization template is created by the linker.
    Note: Persistent data is never cleared or initialized.
  4. If the application has defined user_init functions (see section 14.1.2 Function Attributes), these are invoked. The order of execution depends on link order.
  5. The function main() is called with no parameters.
  6. If main() returns, the processor will reset.

The alternate startup module is linked when the -Wl, --no-data-init option is specified. It performs the same operations, except for step (3), which is omitted. The alternate startup module is smaller than the primary module, and can be selected to conserve program memory if data initialization is not required.

Zipped source code (in dsPIC DSC assembly language) for both modules is provided in the <xc-dsc install directory>\src\libpic30.zip. The startup modules may be modified if necessary. For example, if an application requires main to be called with parameters, a conditional assembly directive may be changed to provide this support.

You can override the normal startup behavior by defining the function int _crt_start_mode(void). This function should return 0 to indicate that a normal start up procedure is used. Any other return value will indicate that preserved variables should not be initialized. If you have not defined this function, the compiler will always initialize everything.