C/C++ Arena

Step 3 of 6

extern and shared state

A global variable defined in one file can be used from another by declaring it with extern:

/* config.h */
extern int max_rounds;     /* declaration: "it exists somewhere" */

/* config.c */
int max_rounds = 30;       /* the one definition */

The declaration goes in a header; the definition goes in exactly one .c file. Two definitions is a linker error, and zero is an "undefined reference" error.

That said, mutable globals are a common source of bugs in large codebases: any code anywhere can change them, and they make testing hard. Prefer passing a struct pointer around. Globals are best kept const.

Your turn: declare max_rounds with extern above main so it can be used before the definition that appears later in the file.

Previous: static functions and variables Next: const-correct interfaces