Topics / Embedded C / Q16
What are weak symbols?
Short answer: A weak symbol is a definition that the linker uses only if no normal (strong) definition with the same name exists. Start-up files define every interrupt handler as a weak alias of a default handler, so when you write a function with the exact same name in your code, your strong definition replaces it, without editing the start-up file.
/* startup.c */
void Default_Handler(void) { for (;;) { } }
void USART1_IRQHandler(void) __attribute__((weak, alias("Default_Handler")));
/* uart.c: this strong definition overrides the weak one */
void USART1_IRQHandler(void)
{
/* real handler */
}
Other uses
- Hooks with default implementations: a library defines
__attribute__((weak)) void app_error_hook(int code) { }and calls it; the application may override it. - Platform overrides: HAL libraries define weak callbacks (
HAL_UART_RxCpltCallback) that you implement in your code. - Optional features:
if (optional_fn) optional_fn();with a weak declaration (extern void optional_fn(void) __attribute__((weak));), which is NULL if no one defines it.
Pitfalls
- Misspelled handler name:
void USART1_IRQHandle(void)(missingr) compiles and links fine; the weak default stays in the vector table, and when the interrupt fires the system hangs inDefault_Handler. When debugging a hang there, check which interrupt is active (SCB->ICSRVECTACTIVEfield). - C++ name mangling: a handler defined in a
.cppfile must beextern "C", or its name will not match. - Static libraries: the linker only pulls an object file out of a
.aarchive to satisfy an undefined reference; it does not search archives to replace a weak definition. A strong override inside a library may therefore be silently ignored unless something else pulls in that object (use--whole-archiveor put the override in a directly linked object). - LTO and weak symbols have had compiler bugs; check the map file to see which definition was used.