Course contentsShow
← C
Lesson 59 of 1,2191. FoundationsFree lesson

Compiling multiple source files

Compiling multiple source files

What you'll learn: How to split your C code into separate files and merge them into a single program using the compiler.

The IKEA Method of Coding

Up until now, you have likely kept all your C code in a single .c file. For tiny projects, that works fine. But as your programs grow, shoving thousands of lines into one file is like putting your clothes, kitchen supplies, and bedsheets into one massive crate. It is hard to find anything, and if you spill coffee on one item, you’ve made a mess of everything.

In the real world, C programmers split their code into logical "modules." You might have one file for your math functions, one for handling user input, and one for the main logic. This makes your code organized, reusable, and easier to debug.

Linking the Pieces

When you have multiple files, the compiler acts like a construction foreman. It processes each file individually and then "links" them together into a final executable.

Imagine you have two files: functions.c (which contains a specific task) and main.c (which runs the program). You don't compile them into two separate programs; you tell the compiler to bake them into one.

// File 1: greetings.c
#include <stdio.h>

void say_hello() {
    printf("Hello from a different file!\n");
}

// File 2: main.c
void say_hello(); // Tell main that this function exists somewhere else

int main() {
    say_hello();
    return 0;
}

How to Compile

To turn these separate files into one program, you list them both in your terminal command. Using the common gcc compiler, it looks like this:

gcc main.c greetings.c -o my_program

The compiler looks at main.c, sees that it needs a function called say_hello, finds that function inside greetings.c, and stitches them together. The result is a single file named my_program that contains the logic from both sources.

This approach is the backbone of professional software development. By keeping files small and focused, you can work on one part of a program without getting lost in the rest of the noise.

Key takeaway

To build a program from multiple files, list every .c file in your compilation command so the compiler can link them into a single executable.