← Back to C Course | Chapter 14: Additional Topics | Lesson 3 of 9

C Multi-file Programming

Modularizing Code

Splitting a growing program across multiple source files keeps each file focused on one area of responsibility, making the overall codebase easier to navigate, easier to test in isolation, and easier for more than one person to work on at the same time.

Example: Modularizing Code

c
#include <stdio.h>
int square(int n) {
	return n * n;
}
int main() {
	printf("%d", square(5));
	return 0;
}

The extern Keyword

The extern keyword tells the compiler that a variable is defined in a different source file and should be linked to that existing definition rather than treated as a brand-new variable, which is what allows a global value to be shared safely across multiple .c files.

Example: The extern Keyword

c
#include <stdio.h>
int sharedCount = 10;
int main() {
	printf("%d", sharedCount);
	return 0;
}

Compiling Multiple Files

Building a multi-file C program means passing every relevant .c file to the compiler in a single command, such as gcc main.c tools.c -o program, so the compiler can compile each file separately and the linker can then stitch their object code together into one executable.

Example: Compiling Multiple Files

c
#include <stdio.h>
int main() {
	printf("Multiple .c files compiled into one program");
	return 0;
}

Sharing Function Prototypes

Putting a function's prototype in a shared header file, then including that header both in the file that defines the function and in every file that calls it, lets the compiler verify each call matches the function's real signature without needing to see the function's actual implementation.

Example: Sharing Function Prototypes

c
#include <stdio.h>
int add(int a, int b);
int main() {
	printf("%d", add(2, 3));
	return 0;
}
int add(int a, int b) {
	return a + b;
}

Benefits of Multi-file Projects

Beyond just organizing code, splitting a project into multiple files lets separate contributors edit different files at the same time with far less risk of merge conflicts, and lets a build system recompile only the files that actually changed rather than the entire project every time.

Example: Benefits of Multi-file Projects

c
#include <stdio.h>
int square(int n) { return n * n; }
int cube(int n) { return n * n * n; }
int main() {
	printf("%d %d", square(3), cube(3));
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.