SLAU646F September 2015 – June 2020
When your program starts running but before execution reaches main(), C Runtime (CRT) startup code initializes global/static data, zero-initializes bss, and calls any functions stored in .init_array (for example, global constructors for C++). The inclusion of functionality during this startup sequence is dynamic, so that functions are linked into the program only if they are required.
CRT functions are each stored in their own section. The linker script sorts these sections by name to enforce the order in which they are executed. You can cause your own functions to run before main() by placing them in a section with a name beginning with “.crt_####”, where #### is a 4-digit decimal number, padded with leading 0s.
It is important to mark these functions with both the “naked” and "used" function attributes. The "naked" attribute removes the function prologue and epilogue, allowing the function to “fall-through” to the next CRT function instead of trying to execute a return instruction. The “used” attribute prevents compiler optimization from removing the function if it is not explicitly called. See Section 5.1.1
User-specified CRT functions may be used to disable the watchdog immediately after program start. This can prevent the watchdog from firing before main(), during initialization of large data or bss sections. For example:
#include <msp430.h>
static void __attribute__((naked, used, section(".crt_0042")))
disable_watchdog (void)
{
WDTCTL = WDTPW | WDTHOLD;
}
The names of existing sections containing CRT startup code are show below. This list can be extracted by looking at the section names in “libcrt.a” and “crt0.o”.
The example above for the disable_watchdog() function would therefore run immediately after the system initializes and branches to “_start” and before bss initialization is performed.