CodeBlanks Logo Icon CodeBlanks

extern

  • C course
  • Intermediate
  • Lesson 60/116
  • 5 min

Learn to share global variables with extern.

The extern keyword

extern declares that a variable is defined in another file. You write extern int counter; in a header; one source file has the definition int counter = 0;. Other files include the header and use counter.

extern is a declaration, not a definition; it allocates no memory. Multiple .c files can share the same global. The definition must appear in exactly one file; otherwise the linker errors. This mechanism is the standard way to share state across modules; used for config flags, counters and error codes.

extern and definition

To share a global: put extern int counter; in the header, and int counter = 0; in one .c file. The definition file is usually the module's own .c; for example counter.c.

When each .c file does #include "counter.h", it sees and uses counter. The initial value in the definition is optional but recommended; uninitialized globals are zero in C, but writing it explicitly is clearer. Multiple definitions are a linker error; keep the one-definition rule.

Practice Use an extern global

Simulate in one file: write extern int counter; declaration, then int counter = 5; definition. In int main(void) add counter += 10; and printf("%d\n", counter);. Don't forget <stdio.h>.

Starter code

main.c
#include <stdio.h>

// Declare counter with extern
// Define counter as 5

int main(void) {
    // Increment counter by 10 and print
    return 0;
}

Sample solution

main.c
#include <stdio.h>

extern int counter;
int counter = 5;

int main(void) {
    counter += 10;
    printf("%d\n", counter);
    return 0;
}

Expected output

15

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the extern declaration

Question
/* config.h */
____ int debug_mode;
Answer
/* config.h */
extern int debug_mode;

Explanation: extern int debug_mode; leaves the definition to another file.

2 If multiple .c files share a global, what happens?

  • No file can define it
  • Definition goes in the header
  • Each file must define it
  • Only one defines it Correct answer

Explanation: One file defines; the others declare with extern.

3 Match extern terms

Term Meaning
extern int x; Header declaration
int x = 0; Source definition
#include "x.h" Header inclusion
linker Merges definitions

All lessons in Intermediate