C Multi-file Programming
In this page:
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
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
printf("%d", square(5));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int sharedCount = 10;
int main() {
printf("%d", sharedCount);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
printf("Multiple .c files compiled into one program");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: