Using keyword extern in C
In this post I will show why keyword extern is useful in large projects on C language with many files.
Let’s make a simple project. Create a file logger.h:
int max_callstack_depth = 3;
Then create file utils.h
#include <stdio.h>void handle_error();
Here we only declare method handle_error.
Implement method in utils.c
#include "utils.h"void handle_error() {
int a = max_callstack_depth;
printf("max_callstack_depth: %d\n", a);
}
Create file main.c
#include <stdio.h>
#include "logger.h"
#include "utils.h"int main() {
handle_error();
}
Let’s compile it:
gcc main.c logger.h utils.c -o main
You will get error:
This means that compiler failed to find our variable max_callstack_depth. To fix this we need to add line in file utils.c
extern int max_callstack_depth;
The whole content of utils.c is following
#include "utils.h"extern int max_callstack_depth;void handle_error() {
int a = max_callstack_depth;
printf("max_callstack_depth: %d\n", a);
}
The “extern” keyword is used to declare and define the external or global variables. Using keyword extern we signal compiler that variable max_callstack_depth is global and should be available across all files in project.