Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Global Variables in C
Chapter 6, Lecture 30 of our free C programming course: learn how global variables in C work, how they are initialised, and when to avoid them in embedded C programming.
Welcome back to the free C programming course on EmbeddedPathashala. In this free C tutorial we study global variables in C: variables declared outside every function so that all functions in the program can read and modify them. Globals are everywhere in embedded C programming. Hardware status flags, configuration tables, counters shared with interrupt handlers and buffers that must survive for the whole life of the device are usually global. They are powerful, but they are also the source of some of the hardest bugs in firmware, so this lecture teaches both the rules and the discipline.
What You Will Learn
- How to declare a global variable and where it lives in memory
- Why globals start at zero while locals do not
- What happens when a local variable has the same name as a global
- How globals are shared between functions and between files
- Why the
volatilekeyword matters for variables shared with interrupts - The risks of globals and the habits that keep them safe
Prerequisites
Read the previous lecture on local variables first, because global variables are best understood by contrast. You also need to be comfortable writing functions and using printf.
What Are Global Variables in C?
A global variable is declared at file level, outside the body of any function. Its scope runs from the declaration to the end of the file, so every function written below it can use it. Its lifetime is the entire run of the program: it is created before main starts and lives until the program ends. Any function can read it, and any function can change it, which is exactly why globals are both convenient and dangerous.
A second feature sets globals apart from locals. Global variables are guaranteed to start at zero if you give no initial value. The C standard calls this static storage duration. On a typical embedded system the startup code clears the uninitialised globals region before calling main, and copies the initial values of initialised globals from flash into RAM.
One global variable shared by every function
Global area: boot_count (starts at 0), threshold (starts at 50)
▲ read and write ▲
main()
Can change threshold.
report()
Reads both globals.
tune()
Increments boot_count.
Global Variables in C: A Working Example
This program declares two globals, one with an initial value and one without. A third variable named threshold is also declared locally inside tune to show which one wins. Save it as ep_globals.c.
#include <stdio.h>
int boot_count; /* global, no initializer */
int threshold = 50; /* global, initialized */
static void report(void)
{
printf("report: boot_count=%d threshold=%d\n", boot_count, threshold);
}
static void tune(void)
{
int threshold = 75; /* local hides the global */
printf("tune: local threshold=%d\n", threshold);
boot_count++;
}
int main(void)
{
report();
tune();
report();
threshold = 60; /* global changed from main */
report();
return 0;
}
gcc -Wall -Wextra -o ep_globals ep_globals.c
./ep_globals
report: boot_count=0 threshold=50
tune: local threshold=75
report: boot_count=1 threshold=50
report: boot_count=1 threshold=60
Understanding the Output
The first line shows boot_count equal to 0 even though we never assigned it. That is the automatic zero initialisation of globals. Inside tune, the local variable named threshold has the value 75, but the global one is untouched, and the next report still prints 50. This is the general rule: when a local and a global share a name, the local variable takes precedence inside its scope. The global is hidden, not destroyed.
The function tune also increments boot_count, and the change is visible afterwards in report. No parameter was passed and nothing was returned. The two functions communicated through the shared global. Finally, main assigned 60 to the global threshold, and the last report confirms it.
This behaviour is what makes global variables in C so different from locals. A local variable disappears when its function returns, so it can never carry information from one call to the next. A global variable has no such limit, so any function can leave a message for any other function simply by writing a value, and the next function to run will find it. That is the power of globals, and also the reason a careless write in one corner of the program can break a function in a completely different corner. Keep the comparison below in mind whenever you decide where a variable should live.
| Feature | Local variable | Global variable |
|---|---|---|
| Declared | Inside a function or block | Outside all functions |
| Visible to | That block only | All functions below the declaration |
| Lifetime | While the block runs | Entire program |
| Default value | Undefined | Zero |
| Typical storage | Stack or register | Fixed RAM address |
Sharing Global Variables Between Source Files
Real firmware projects have many .c files. A global defined in one file can be used in another if the second file contains a declaration using the extern keyword, usually placed in a shared header. The definition, which actually reserves memory, must appear in exactly one file.
/* ep_config.h */
extern int threshold; /* declaration: no memory reserved */
/* ep_config.c */
int threshold = 50; /* definition: memory reserved here */
If you want a global to be private to one file, add static in front of it. It still lives for the whole program, but other files cannot link to it. This is one of the cheapest ways to avoid accidental sharing.
Global Variables and Interrupts: The volatile Keyword
In embedded systems a global often serves as the mailbox between an interrupt handler and the main loop. The compiler does not know that an interrupt can change the variable at any moment, so it may optimise away repeated reads and the main loop could wait forever. Declaring such a variable volatile forces a real memory read on every access.
volatile int data_ready; /* set to 1 inside the UART interrupt */
void main_loop(void)
{
while (!data_ready) {
/* wait */
}
data_ready = 0;
}
Important: volatile stops the compiler caching the value, but it does not make multi-step updates atomic. For counters or larger structures shared with interrupts, protect the access by briefly disabling interrupts or by using an atomic operation.
When Global Variables in C Are the Right Choice
- Hardware state: flags that represent the device, such as “motor running”.
- Large buffers: a 1 KB receive buffer is safer as a global than as a local array that would flood a small stack.
- Interrupt communication: volatile flags and counters shared with handlers.
- Configuration data: tables and settings used throughout the program.
Common Mistakes with Global Variables
Accidental shadowing. Declaring a local with the same name as a global means your assignment changes the local copy and the global stays as it was. The gcc option -Wshadow catches it.
Too many globals. When fifty functions can change a variable, finding the one that corrupted it becomes a detective job.
Missing volatile. A loop that works at optimisation level 0 and hangs at -O2 is the classic symptom.
Name collisions across files. Two files that each define a global with the same name cause a linker error or, worse, silent merging with older toolchains. Use a clear prefix, such as motor_speed rather than speed.
Best Practices, Performance and Security
- Use as few globals as you can. Pass values through parameters and return values when possible.
- Mark file-private globals
static. - Give every global a descriptive name or module prefix.
- Mark variables shared with interrupts
volatile, and guard compound updates. - Remember that every global consumes RAM for the entire life of the device, so avoid large unused ones.
- Treat globals that hold secrets, such as keys, with care. They stay in memory permanently, so overwrite them when no longer needed.
- Keep read-only tables
constso the linker can place them in flash and save RAM.
Summary and Key Takeaways
- Global variables in C are declared outside all functions and are usable by every function after the declaration.
- They exist for the entire program and are automatically initialised to zero.
- A local variable with the same name takes precedence inside its own scope.
- Use
externto share a global between files andstaticto keep it private. - Use
volatilefor variables changed by interrupts, and keep the number of globals small.
Conclusion
Global variables in C give you shared state that survives the whole run of a program, and they are indispensable for hardware flags and large buffers. The price is reduced clarity: every function becomes a possible author of every change. The professional habit is to choose each global deliberately, name it carefully, hide it with static where possible, and document who may write it. In the next lecture we meet a middle path, the static variable, which remembers its value between calls like a global but stays visible only inside one function.
Frequently Asked Questions
What is a global variable in C?
A variable declared outside every function. All functions that appear after the declaration can access and modify it.
What is the default value of a global variable?
Zero. Global and static variables are cleared automatically before main starts.
What happens if a local and a global have the same name?
The local variable takes precedence inside its scope. The global remains unchanged and hidden.
How do I use a global from another file?
Define it in one file and declare it with extern in the others, normally through a shared header file.
Why use volatile on a global variable?
It tells the compiler the value can change outside the normal program flow, such as inside an interrupt, so it must reread memory every time.
Are global variables bad practice?
Not always, but they make code harder to test and debug. Use them sparingly and keep them private to a file when possible.
Keep Going With the Free Embedded C Course
Continue to the next lecture on static variables, share this free C tutorial with a friend, and keep building your embedded C programming skills.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

1 Comment