How to Share Variables between Modules When Programming in C

By Dan Gookin

The best way to share a variable between several functions in a huge C programming project is to make that variable global. The global variable needs to be declared in only one module, usually the main module. For the other modules to access that variable, they must employ the extern keyword.

The extern keyword doesn’t declare a global variable. It merely tells the compiler that somewhere, in some other module, a global variable is to be found. That way, the compiler doesn’t freak out. Here’s the extern keyword’s format:

extern type name

type is a variable type, the same type as the global variable being referenced. name is the global variable’s name. Getting both the type and name correct is what keeps the compiler happy.

Like a global variable, the extern statement is generally found at the top of the source code, not within any specific function.

Code for main.c and a Global Variable shows the main module, with the second() function prototyped at Line 4. The prototype is required because the second() function is called at Line 11. You don’t need to prototype all functions in another module, only those referenced or called.

CODE FOR MAIN.C AND A GLOBAL VARIABLE

#include <stdio.h>
#include <stdlib.h>
void second(void);
int count;
int main()
{
  for(count=0;count<5;count++)
    second();
  return 0;
}

Global variable count is declared at Line 6. It’s used in the for loop at Line 10, but it’s also used in the second.c source code file.

CODE FOR SECOND.C USING THE GLOBAL VARIABLE

#include <stdio.h>
extern int count;
void second(void)
{
  printf("%dn",count+1);
}

The second.c source code file uses the global variable count, which is declared in the main.c file. To properly access that global variable, Line 3 identifies the variable as an external int. The count variable is then used in the second() function — specifically, at Line 7.

Exercise 1: Create a new project in Code::Blocks that incorporates both source code files shown. Build and run.