C: Multi-File Programming

🗓 Last updated: 2026-11-30👤 Written by: Gray✓ Reviewed by: MOTO🏷 Category: C Tutorial

Multi-file programming is like team collaboration — declarations are contracts (header files), implementations are the work (source files), extern is a cross-department reference, and Makefile is the project schedule.

Reference entries in this section: extern #ifndef #include

1. Why Multi-File

A single .c file is enough for small programs, but real projects have large codebases that need to be split by functionality into multiple files:


2. Writing Header Files

Header files (.h) contain declarations, and source files (.c) contain definitions. This is the most fundamental modularization rule in C.

(1) Header File Content

C
// Preprocessor directive
#ifndef MATH_UTILS_H
// Preprocessor directive
#define MATH_UTILS_H

// Function definition
int add(int a, int b);
// Function definition
int subtract(int a, int b);
// Function definition
double average(int *arr, int n);

// Preprocessor directive
#endif

(2) Source File Content

C
// Preprocessor directive
#include "math_utils.h"

// Function definition
int add(int a, int b) {
    // Return result
    return a + b;
}

// Function definition
int subtract(int a, int b) {
    // Return result
    return a - b;
}

// Function definition
double average(int *arr, int n) {
    // Conditional check
    if (n <= 0) return 0.0;
    // Variable declaration
    int sum = 0;
    // For loop
    for (int i = 0; i < n; i++) sum += arr[i];
    // Return result
    return (double)sum / n;
}

(3) Main Program

TEXT
#include <stdio.h>
#include "math_utils.h"

int main(void) {
    printf("3 + 5 = %d\n", add(3, 5));
    printf("10 - 4 = %d\n", subtract(10, 4));
    int scores[] = {80, 90, 75, 88};
    printf("Average: %.1f\n", average(scores, 4));
    return 0;
}
💡 Tip: Header files should only contain declarations (function prototypes, type definitions, macros, extern declarations), not definitions (function bodies, variable initializations). Duplicate definitions cause linker errors.


3. extern for Cross-File References

A global variable defined in one .c file can be accessed from other files using extern.

(1) Definition (in some .c file)

C
// Variable declaration
int g_count = 0;

(2) Declaration (in a header or another .c file)

C
extern int g_count;

extern tells the compiler "this variable is defined elsewhere — this is only a declaration," so no new space is allocated.

▶ Example

Project structure:

TEXT
project/
├── counter.h
├── counter.c
└── main.c

counter.h:

C
// Preprocessor directive
#ifndef COUNTER_H
// Preprocessor directive
#define COUNTER_H

extern int g_count;
// Function definition
void increment(void);
// Function definition
int get_count(void);

// Preprocessor directive
#endif

counter.c:

TEXT
#include "counter.h"

int g_count = 0;

void increment(void) {
    g_count++;
}

int get_count(void) {
    return g_count;
}

main.c:

C
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include "counter.h"

// Function definition
int main(void) {
    increment();
    increment();
    increment();
    // I/O operation
    printf("count = %d\n", get_count());
    // I/O operation
    printf("g_count = %d\n", g_count);
    // Return result
    return 0;
}
TEXT
count = 3
g_count = 3
⚠️ Note: Do not include an initializer in an extern declaration. extern int g_count = 0; may become a definition on some compilers, causing duplicate definition errors.


4. Multi-File Compilation Commands

BASH
gcc -c counter.c -o counter.o
gcc -c main.c -o main.o
gcc counter.o main.o -o myapp

The -c flag compiles without linking, producing .o object files. All .o files are then linked into the final executable.

(2) Compile All at Once

BASH
gcc counter.c main.c -o myapp

Simple, but changing any file requires recompiling everything — not suitable for large projects.

💡 Tip: The advantage of individual compilation: if you change main.c, you only need gcc -c main.c and then link, without recompiling counter.c.


5. Makefile Basics

Makefile automates compilation rules and only recompiles files that have been modified.

MAKEFILE
CC = gcc
CFLAGS = -Wall -g

myapp: main.o counter.o
	$(CC) $(CFLAGS) main.o counter.o -o myapp

main.o: main.c counter.h
	$(CC) $(CFLAGS) -c main.c -o main.o

counter.o: counter.c counter.h
	$(CC) $(CFLAGS) -c counter.c -o counter.o

clean:
	rm -f *.o myapp
⚠️ Note: Makefile indentation must use Tab characters, not spaces. This is the most common mistake for beginners.

Usage:

BASH
make
make clean

Makefile rule format:

MAKEFILE
target: dependencies
	command

6. Preventing Duplicate Inclusion

A header file may be included by multiple source files, and the same source file may indirectly include it multiple times. Without protection, duplicate declarations cause errors.

(1) Approach 1: Include Guard

C
// Preprocessor directive
#ifndef MYHEADER_H
// Preprocessor directive
#define MYHEADER_H

// Function definition
void my_func(void);

// Preprocessor directive
#endif

On first inclusion, MYHEADER_H is undefined, so the content is processed and the macro is defined. On subsequent inclusions, #ifndef evaluates to false and the entire content is skipped.

(2) Approach 2: #pragma once

C
// Preprocessor directive
#pragma once

// Function definition
void my_func(void);

Concise and supported by most compilers, but not part of the standard — theoretically less portable than include guards.

💡 Tip: Both approaches are used in practice. #pragma once is more concise; include guards are more standard. Pick one and use it consistently.


7. Header File Organization Principles

▶ Example 3: Static vs External Functions

▶ Try it Yourself
C
// helpers.c
#include <stdio.h>
#include "helpers.h"

int global_counter = 0;  // definition

static void secret_log() {
    printf("  [secret internal log]\n");
}

void public_greet(const char *name) {
    global_counter++;
    printf("Hello, %s! (call #%d)\n", name, global_counter);
    secret_log();  // only visible inside helpers.c
}
C
// main.c
#include "helpers.h"

int main() {
    public_greet("Alice");
    public_greet("Bob");
    return 0;
}

编译: gcc -c main.c helpers.c && gcc main.o helpers.o -o greet && ./greet 输出:

TEXT
Hello, Alice! (call #1)
  [secret internal log]
Hello, Bob! (call #2)
  [secret internal log]

▶ Example 4: Traditional Include Guards

▶ Try it Yourself
C
// math_tools.c
#include "math_tools.h"

double add(double a, double b) {      // definition
    return a + b;
}

double multiply(double a, double b) { // definition
    return a * b;
}
C
// app.c
#include <stdio.h>
#include "math_tools.h"   // includes the declaration only

int main() {
    // Use the functions — definitions live in math_tools.c
    printf("2.5 + 3.5 = %.1f\n", add(2.5, 3.5));
    printf("2.5 * 3.5 = %.1f\n", multiply(2.5, 3.5));
    return 0;
}

编译: gcc -c math_tools.c -o math_tools.o && gcc -c app.c -o app.o && gcc math_tools.o app.o -o app && ./app 输出:

TEXT
2.5 + 3.5 = 6.0
2.5 * 3.5 = 8.75

Reference entries in this section: extern #ifndef #include

❓ FAQ

Q What does "static" mean in C?
A static has two meanings depending on scope. At file scope (global variable or function), static gives internal linkage — the symbol is not visible outside the file. At function scope (local variable), static keeps its value between function calls with function-local lifetime but file-wide scope.
Q How do I use extern to share variables between source files?
A Define the variable in exactly one .c file with int global_count;. In every other .c file that needs it, declare with extern int global_count; — this tells the compiler the definition is elsewhere and the linker will resolve it. Declarations go in the shared header; the definition stays in one .c file.
Q What is the difference between using a Makefile and CMake to compile the code?
A Make is a low-level build tool — you write rules for shell commands. CMake is a meta-build system that generates makefiles (or Visual Studio projects, Ninja files, etc.) from platform-independent CMakeLists.txt. For small single-tech projects, make is simpler; for cross-platform large projects, CMake is industry standard.
Q What is the difference between static and shared libraries?
A Static libraries (.a on Unix, .lib on Windows) are copied into the executable at link time — the final binary is larger but has no runtime dependency. Shared libraries (.so on Unix, .dll on Windows) are loaded at runtime by the OS dynamic linker — binaries are smaller but the library file must be present on the target system.
Q What is a "static" function in C?
A A static function has internal linkage — its name is not exported to the linker symbol table. This is a namespacing technique for file-local helper functions. Two .c files can have static functions with the same name without conflicts, unlike regular functions.
Q Can I put variable definitions in a header file?
A No. If a header with a variable definition is included by multiple .c files, you get multiple definitions and the linker will report "multiple definition" errors. Headers should contain declarations (extern int count;); actual definitions belong in one .c file.
Q Should I choose pragma once or include guards?
A Pick one and be consistent. Include guards are standard C, portable, and work everywhere. #pragma once is simpler but non-standard and can fail with unusual file setups. Most large open-source C/C++ projects use include guards to avoid pragma once portability issues.
Q What is the difference between #include <> and #include ""?
A #include <file.h> searches the compiler's standard include paths. #include "file.h" searches the current source file's directory first, then falls back to system paths. Use <> for system and third-party headers; use "" for your own project headers.

📖 Summary

📝 Exercises

  1. Create a 3-file project: string_utils.h, string_utils.c, and main.c. Implement a string reversal function and a character-count function, then call and test them in main
  2. Write a Makefile for exercise 1 that supports make to compile and make clean to clean up
  3. Intentionally omit duplicate-inclusion protection in a header file, then #include the same header twice in main.c and observe the compilation error
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏