Topics / C Programming / Q4
What is the use of the extern keyword?
Short answer: extern declares a variable or function that is defined somewhere else (usually in another .c file), so this file can use it and the linker connects the two. Functions are extern by default, so the keyword is mainly needed for global variables.
/* config.h */
extern uint32_t g_system_clock_hz; /* declaration */
/* config.c */
uint32_t g_system_clock_hz = 16000000; /* the one definition */
/* uart.c */
#include "config.h"
void uart_init(void) { uint32_t div = g_system_clock_hz / 115200; /* ... */ }
Rules
extern int x;does not allocate memory.extern int x = 5;is a definition (the initialiser wins), which compilers warn about.- An
externdeclaration inside a function refers to a global defined elsewhere. extern "C"in C++ is a different feature: it turns off C++ name mangling so C and C++ code can call each other. C headers used from C++ wrap their declarations in#ifdef __cplusplus extern "C" { #endif.
Linker errors: if no file defines the variable, you get undefined reference; if two files define it, multiple definition.
Design advice: many global variables shared through extern make firmware hard to reason about, because any file can change them. Prefer static variables with access functions (clock_get_hz()), and keep extern for a few genuinely global items such as linker-script symbols:
extern uint32_t _sdata, _edata, _sidata; /* defined by the linker script, used by start-up code */
These linker symbols have no storage of their own; only their address is meaningful (&_sdata).