Search code examples
assemblymicrocontrollerstartup

What is a startup code in C for Microcontrollers ? When / Why / How it should be modified?


This is a general question about startup code. I know it's like the bootloader or the first thing that run after reset or power up and it call the main function.

But i want to know it main / core functionnalities.

For example (Searching in google),

Startup code is executed immediately upon reset of the target system. The Keil startup code performs (optionally) the following operations in order:

 Clears internal data memory
 Clears external data memory
 Clears paged external data memory
 Initializes the small model reentrant stack and pointer
 Initializes the large model reentrant stack and pointer
 Initializes the compact model reentrant stack and pointer
 Initializes the 8051 hardware stack pointer
 Transfers control to code that initializes global variables or to the main C function if
there are no initialized global variables

Nb: The startup code is always written in assembly since it depend on the CPU target.

Thanks for your time


Solution

  • You mentioned that the startup code calls main so I'll assume that you are talking about startup code for a C/C++ application. The startup code is responsible for setting up the C run-time environment for the application. That includes:

    • copying the initial values of initialized variables from ROM to RAM
    • zeroing out the RAM for uninitialized variables
    • setting up the stack pointer
    • for C++ applications, it calls the constructors for any global or static object instances
    • finally, call main

    The startup code may also do some hardware initialization but this is hardware specific and not necessarily a requirement. For example, If the hardware uses a PLL to raise the clock frequency then the startup code might setup the PLL first thing so that the remaining startup code executes at full speed. If the board has external devices on the address/data bus then the processor's external memory controller is typically configured in the startup code. Or if the hardware has a watchdog then the startup code might disable it so that it doesn't reset before the application has an opportunity to configure it.

    I don't typically do application specific hardware initialization in the startup code. Rather, I will initialize GPIO, timers, and serial ports within my application, after main is called.

    The compiler tool chain typically provides startup code for the hardware environments that it supports. This example startup code is probably fine for most applications and you may never have to modify it. But if there is something specialized about your hardware or run-time environment then you may need to customize the startup code. When I have had to customize the startup code I have always just taken the example startup code and modified it to suit my needs. I don't remember ever writing startup code from scratch.