These are the notes for C episode 20. Until now every program lived in one main.c. Real programs (the Linux kernel, gcc itself, the app on your phone) are spread over hundreds or thousands of files. In this episode you cut a program into two files, watch the build break in three different ways, and invent the fixes one by one: declarations (prototypes), your own header file, include guards, extern and static, and finally separate compilation with gcc -c and make. Every example was compiled with gcc 13. Single-file examples use the SyntaxPilot compiler's command, gcc -O2 -Wno-unused-result main.c -o main -lm; the multi-file builds were run in a real terminal (bash on Linux), because the online compiler compiles one file.
The problem: one cook, one giant file
Real-life example: the dhaba with one cook. A small roadside dhaba has one cook who makes the rotis, the curry, the chai and writes the bills. With ten customers a day that works. When the dhaba gets famous and has a hundred orders an hour, everything slows down, and changing the curry recipe mixes up the bills. So the owner splits the kitchen into stations (tandoor, curry, billing), and puts a menu card on the wall so the waiter knows what each station can make without walking into the kitchen.
One main.c has the same problems as the one-cook dhaba:
- The bill splitter from episode 19 was already 50 lines. Add GST, discounts, a menu, receipts, and it grows into thousands of lines.
- Two people can't comfortably edit the same file at the same time.
- Every small change recompiles everything.
Idea: one file per job. Keep main in main.c and move the bill maths into bill.c.
The obvious attempt: cut the file in two
// main.c
#include <stdio.h>
int main() {
double total = with_gst(1000);
printf("Total: Rs %.2f\n", total);
return 0;
}
// bill.c
double with_gst(double amount) {
return amount * 1.05;
}
Failure 1: compile only main.c
$ gcc main.c -o app
main.c: In function 'main':
main.c:4:20: warning: implicit declaration of function 'with_gst' [-Wimplicit-function-declaration]
4 | double total = with_gst(1000);
| ^~~~~~~~
/usr/bin/ld: /tmp/cc35t5Qz.o: in function `main':
main.c:(.text+0x17): undefined reference to `with_gst'
collect2: error: ld returned 1 exit status
Two different tools are complaining:
- The compiler (warning): it reached line 4 and had never heard of
with_gst. An implicit declaration means C invented a declaration for you. - The linker
ld(error): the linker joins the compiled pieces into one program, and it could not find the function's body anywhere: undefined reference.
Failure 2: compile both files, get a wrong answer
$ gcc main.c bill.c -o app
main.c:4:20: warning: implicit declaration of function 'with_gst' [-Wimplicit-function-declaration]
$ ./app
Total: Rs 0.00
The linker is happy now, but the answer is 0.00, not 1050.00. No crash, no error: the worst kind of bug.
Why: C guessed that the function returns int
Put everything in one file with the function after main and gcc tells you what it assumed:
#include <stdio.h>
int main() {
double total = with_gst(1000);
printf("Total: Rs %.2f\n", total);
return 0;
}
double with_gst(double amount) {
return amount * 1.05;
}
main.c:4:20: warning: implicit declaration of function 'with_gst' [-Wimplicit-function-declaration]
main.c: At top level:
main.c:9:8: error: conflicting types for 'with_gst'; have 'double(double)'
main.c:4:20: note: previous implicit declaration of 'with_gst' with type 'int()'
When C meets a function it has never seen, old C rules make it guess int with_gst(): returns an int, takes anything. In one file gcc later sees the truth and reports the conflict. In two files it never sees the truth, so main read a double result as if it were an int, and printed garbage. (Since C99 this implicit declaration is not allowed by the standard; gcc 13 still accepts it with a warning, gcc 14 makes it an error. Either way: never ignore this warning.)
Declarations (prototypes) vs definitions
The fix is to tell the compiler about the function before it is used:
#include <stdio.h>
double with_gst(double amount); // declaration (prototype)
int main() {
double total = with_gst(1000);
printf("Total: Rs %.2f\n", total);
return 0;
}
double with_gst(double amount) { // definition
return amount * 1.05;
}
Output:
Total: Rs 1050.00
Real-life example: the menu card and the kitchen. The menu card says "Paneer roll, Rs 90": what exists and what it costs. That is a declaration. The cook who actually makes the roll is the definition. The waiter only reads the card to take your order and never enters the kitchen: the compiler only needs the declaration to check your call; later the linker fetches the real definition from the other file.
| Declaration | Definition | |
|---|---|---|
| Looks like | double with_gst(double amount); |
double with_gst(double amount) { ... } |
| Tells the compiler | name, parameter types, return type | the same, plus the body (the real code) |
| How many allowed | as many as you like (they must agree) | exactly one in the whole program |
| Used by | the compiler, to check calls | the linker, to connect calls to code |
The next problem: every .c file that calls with_gst needs that declaration at the top. Twenty files, twenty copies. Change the function one day, forget one copy, and you are back to wrong answers.
Your own header file
Real-life example: one printed menu for every table. A restaurant prints the menu once and every table gets the same copy. When a price changes, it reprints one menu.
- The printed menu is a header file: a file ending in
.hthat holds declarations. - Each table getting a copy is
#include: the preprocessor (episode 16) literally pastes the header's text into the file. - Changing a price is editing
bill.honce: every file that includes it sees the change.
// bill.h
double with_gst(double amount);
// main.c
#include <stdio.h>
#include "bill.h"
int main() {
double total = with_gst(1000);
printf("Total: Rs %.2f\n", total);
return 0;
}
// bill.c
#include "bill.h"
double with_gst(double amount) {
return amount * 1.05;
}
$ gcc main.c bill.c -o app
$ ./app
Total: Rs 1050.00
No warning, correct answer.
"quotes" vs <angle brackets>
| Form | Meaning | Use it for |
|---|---|---|
#include <stdio.h> |
search the system's include folders | the C library and installed libraries |
#include "bill.h" |
search the folder of the current file first, then the system folders | your own headers |
What goes where
In the .h (the menu) |
In the .c (the kitchen) |
|---|---|
| function prototypes | function bodies |
struct, enum, typedef types |
variables with values (definitions) |
#define constants and macros |
static helper functions |
extern declarations of shared variables |
Two habits:
bill.cincludes its ownbill.h. If the declaration and the definition ever disagree, the compiler reports it right there instead of giving wrong answers later.- Never
#includea.cfile. You would paste a whole definition into every file that includes it.
Include guards
The project grows. bill.h gets a struct item (a menu item with a name and a price), and a second header split.h also needs that struct, so it includes bill.h:
// bill.h (no guard yet)
struct item {
char name[20];
double price;
};
double with_gst(double amount);
// split.h
#include "bill.h"
double share(double total, int people);
main.c includes both, and the build fails:
$ gcc main.c bill.c -o app
In file included from split.h:1,
from main.c:3:
bill.h:1:8: error: redefinition of 'struct item'
1 | struct item {
| ^~~~
In file included from main.c:2:
bill.h:1:8: note: originally defined here
Nobody wrote the struct twice, but bill.h was pasted twice: once directly and once through split.h. This is what main.c looks like after the pasting (you can run this one in the online compiler):
#include <stdio.h>
// pasted by #include "bill.h"
struct item {
char name[20];
double price;
};
// pasted again by #include "split.h"
struct item {
char name[20];
double price;
};
int main() {
struct item chai = {"Masala chai", 20};
printf("%s: Rs %.2f\n", chai.name, chai.price);
return 0;
}
main.c:10:8: error: redefinition of 'struct item'
main.c:4:8: note: originally defined here
A function may be declared twice; a type may only be defined once in a file.
Real-life example: the attendance register. A teacher doesn't mark Riya present twice. She first checks the register (already marked?), ticks the name if not, and skips her the second time.
#ifndef BILL_H // if BILL_H is not defined yet...
#define BILL_H // ...define it (the tick)
struct item {
char name[20];
double price;
};
double with_gst(double amount);
#endif // the second paste skips everything up to here
Wrap each pasted copy in the guard and the same one-file program compiles and prints:
Masala chai: Rs 20.00
The first copy defines BILL_H; the second copy finds it already defined and is skipped by the preprocessor.
- Name the guard after the file:
BILL_Hforbill.h,SPLIT_Hforsplit.h. Every header needs its own unique name. #pragma onceat the top of a header does the same job in one line. It is not part of the C standard, but gcc, clang and MSVC all support it.
extern: one global variable shared by many files
Both files need the GST rate, so someone puts a variable in the header:
// bill.h
double gst_rate = 0.05; // a definition in a header: wrong
$ gcc main.c bill.c -o app
/usr/bin/ld: /tmp/cct9z5sX.o:(.data+0x0): multiple definition of `gst_rate'; /tmp/ccdvzE6m.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
The include guard doesn't help: guards only stop a double paste inside one file. main.c and bill.c are compiled separately, each got its own gst_rate, and the linker found two variables with one name.
The fix is the same idea as for functions: declaration in the header, definition in exactly one .c file.
// bill.h
extern double gst_rate; // declaration: "it exists in some other file"
// bill.c
double gst_rate = 0.05; // definition: the one real variable
extern means: this variable exists, but it is defined somewhere else; the linker will find it.
static: private to one file
The opposite of sharing. A helper that only bill.c needs gets the word static (you met it in episode 17):
static double round2(double x) {
return (long)(x * 100 + 0.5) / 100.0;
}
A static function or global variable is visible only inside its own .c file. Other files can't call it, and its name can't clash with a function of the same name in another file. Like the cook's own spice mix: it never goes on the menu. If another file tries extern int count; for a static int count in counter.c, the build fails with undefined reference to 'count' (see practice 3).
Separate compilation: gcc -c, .o files and linking
Building has always been two steps; gcc main.c bill.c -o app just hides them.
| Step | Command | Makes |
|---|---|---|
Compile (one .c at a time) |
gcc -c main.c |
main.o, an object file: machine code with some names still unresolved |
| Compile | gcc -c bill.c |
bill.o |
| Link | gcc main.o bill.o -o app |
app, the program: every name connected to its code |
$ gcc -c main.c
$ gcc -c bill.c
$ ls *.o
bill.o main.o
$ gcc main.o bill.o -o app
$ ./app
GST: 5%
Total: Rs 1050.00
The payoff: change only bill.c, and you recompile only bill.c, then link again:
$ gcc -c bill.c && gcc main.o bill.o -o app
In a project with thousands of files this turns a rebuild of many minutes into seconds.
A first Makefile
make remembers the commands and rebuilds only what changed. A Makefile lists targets, what each one depends on, and the command to build it. The command line must start with a Tab character, not spaces.
app: main.o bill.o
gcc main.o bill.o -o app
main.o: main.c bill.h
gcc -c main.c
bill.o: bill.c bill.h
gcc -c bill.c
$ make
gcc -c main.c
gcc -c bill.c
gcc main.o bill.o -o app
$ touch bill.c # pretend we edited it
$ make
gcc -c bill.c
gcc main.o bill.o -o app
$ make
make: 'app' is up to date.
make compares file times: a target is rebuilt only when one of the files it depends on is newer. Listing bill.h as a dependency means that editing the header rebuilds both object files. If the command lines start with spaces, make stops with Makefile:2: *** missing separator. Stop.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
gcc main.c (forgot bill.c) |
undefined reference to 'with_gst' |
The linker can't find the body | gcc main.c bill.c -o app |
| Calling a function with no prototype | warning: implicit declaration of function 'with_gst' and possibly wrong results |
C guessed it returns int |
#include "bill.h" |
Function defined after main, no prototype |
error: conflicting types for 'with_gst' |
The implicit int() guess conflicts with the real type |
Prototype at the top, or a header |
| Header without a guard, included twice | error: redefinition of 'struct item' |
Pasted twice into one file | #ifndef BILL_H / #define BILL_H / #endif |
double gst_rate = 0.05; in a header |
multiple definition of 'gst_rate' |
Every .c got its own copy |
extern in the .h, the definition in one .c |
#include "bill.c" |
multiple definition errors once two files do it |
A .c holds definitions |
Include only headers |
| Spaces instead of a Tab in a Makefile | *** missing separator. Stop. |
make needs a Tab before commands |
Use a real Tab |
#include <bill.h> |
fatal error: bill.h: No such file or directory |
Angle brackets skip your folder | #include "bill.h" |
Mini project: the bill splitter in three files
// bill.h
#ifndef BILL_H
#define BILL_H
struct item {
char name[20];
double price;
};
extern double gst_rate;
double with_gst(double amount);
double share(double total, int people);
#endif
// bill.c
#include "bill.h"
double gst_rate = 0.05;
static double round2(double x) {
return (long)(x * 100 + 0.5) / 100.0;
}
double with_gst(double amount) {
return round2(amount + amount * gst_rate);
}
double share(double total, int people) {
return round2(total / people);
}
// main.c
#include <stdio.h>
#include "bill.h"
int main() {
struct item order[] = {
{"Masala chai", 20}, {"Samosa", 15},
{"Paneer roll", 90}, {"Lassi", 40}
};
double sum = 0;
for (int i = 0; i < 4; i++) {
printf("%-12s Rs %6.2f\n", order[i].name,
order[i].price);
sum += order[i].price;
}
double total = with_gst(sum);
printf("With %.0f%% GST: Rs %.2f\n",
gst_rate * 100, total);
printf("Each of 3 pays: Rs %.2f\n",
share(total, 3));
return 0;
}
$ gcc -Wall main.c bill.c -o split
$ ./split
Masala chai Rs 20.00
Samosa Rs 15.00
Paneer roll Rs 90.00
Lassi Rs 40.00
With 5% GST: Rs 173.25
Each of 3 pays: Rs 57.75
main.c never sees the body of with_gst or round2: it only knows the menu card, bill.h. -Wall turns on gcc's most useful warnings; the build prints none.
Practice
- Add
double discount(double amount, double percent)to the bill splitter: define it inbill.c, declare it inbill.h, and use it frommainfor a 10% discount on Rs 165 before GST. - Write a Makefile for the three-file bill splitter and run
maketwice. - Write a
countermodule:counter.ckeeps a privatecount,counter.hoffersnext_token()andtokens_given(). Show that another file can't touchcountdirectly. - Remove the include guard from
bill.h, include it twice inmain.c, and read the error. Then fix it with#pragma onceinstead.
Solutions
1. Discount (verified). In bill.h, under the other prototypes:
double discount(double amount, double percent);
At the end of bill.c (it can use the static helper round2 because it's in the same file):
double discount(double amount, double percent) {
return round2(amount - amount * percent / 100);
}
// main.c
#include <stdio.h>
#include "bill.h"
int main() {
double sum = 165;
double after = discount(sum, 10);
printf("After 10%% off: Rs %.2f\n", after);
printf("With GST: Rs %.2f\n", with_gst(after));
return 0;
}
After 10% off: Rs 148.50
With GST: Rs 155.93
2. Makefile. The same shape as above, with the program named split (each command line starts with a Tab):
split: main.o bill.o
gcc main.o bill.o -o split
main.o: main.c bill.h
gcc -Wall -c main.c
bill.o: bill.c bill.h
gcc -Wall -c bill.c
The first make runs all three commands; the second prints make: 'split' is up to date.
3. A private counter (verified):
// counter.h
#ifndef COUNTER_H
#define COUNTER_H
void next_token(void);
int tokens_given(void);
#endif
// counter.c
#include "counter.h"
static int count = 0;
void next_token(void) {
count++;
}
int tokens_given(void) {
return count;
}
// main.c
#include <stdio.h>
#include "counter.h"
int main() {
for (int i = 0; i < 3; i++)
next_token();
printf("Tokens given: %d\n", tokens_given());
return 0;
}
$ gcc -Wall main.c counter.c -o app && ./app
Tokens given: 3
A file that writes extern int count; and then count = 99; fails to link with undefined reference to 'count': static hid it. This is how C does what other languages call encapsulation (private data behind public functions).
4. Without the guard you get error: redefinition of 'struct item'. With #pragma once as the first line of bill.h, the second include is skipped and the program builds.
Quick quiz
A header tax.h is included by five different .c files. Which line is safe to put in it?
- A.
int count = 0; - B.
int add(int a, int b) { return a + b; } - C.
extern int count; - D.
#include "tax.c"
Answer
C: extern int count; It is only a declaration. A and B are definitions, so every one of the five files would get its own copy and the linker would report multiple definition. D pastes a whole .c file (definitions again) into all five.
Interview questions
- What is the difference between a declaration and a definition in C? How many of each may a program have?
- What is a function prototype, and what happens if you call a function without one?
- What do "undefined reference" and "multiple definition" errors mean? Which tool reports them?
- What is the difference between
#include <file.h>and#include "file.h"? - What is an include guard? How is it different from
#pragma once? - Why don't include guards prevent a "multiple definition" linker error for a global variable?
- What does
externdo? What doesstaticdo to a function or a global variable? - What is an object file (
.o)? What is the difference between compiling and linking? - Why do large projects compile files separately? What does
makedo? - What should and shouldn't go in a header file?
- What is a translation unit? (One
.cfile after the preprocessor has pasted in all its includes; the compiler works on one at a time.)
Glossary
| Term | Meaning | Example |
|---|---|---|
| Multi-file program | A program whose source code is split into several .c files |
main.c + bill.c |
| Source file | A .c file with code you write |
bill.c |
| Header file | A .h file of declarations, types and macros, shared with #include |
bill.h |
#include |
A preprocessor command that pastes another file's text in its place | #include "bill.h" |
| Preprocessor | The step before compiling that handles #include, #define, #ifndef |
episode 16 |
| Declaration | Tells the compiler a name and its type, without creating the code or storage | double with_gst(double amount); |
| Definition | Creates the function's code or the variable's storage; exactly one per program | double gst_rate = 0.05; |
| Prototype | A function declaration with its parameter types | double share(double total, int people); |
| Implicit declaration | A declaration C invents for an unknown function (assumes it returns int) |
the with_gst warning |
| Compiler | Turns one .c file into machine code (an object file) |
gcc -c bill.c |
| Object file | Compiled machine code from one .c file, with some names still unresolved |
bill.o |
| Linker | Joins object files into one program and connects every name to its code | ld, run by gcc main.o bill.o -o app |
| Undefined reference | Linker error: a name is used but never defined in any linked file | forgot bill.c |
| Multiple definition | Linker error: the same name is defined in two files | a variable defined in a header |
| Include guard | #ifndef X / #define X / #endif around a header, so a second paste is skipped |
BILL_H |
#pragma once |
A one-line, non-standard but widely supported alternative to an include guard | first line of bill.h |
extern |
Declares a variable defined in another file | extern double gst_rate; |
static (file scope) |
Makes a function or global visible only in its own .c file |
static double round2(double x) |
| Global variable | A variable defined outside every function, visible to the whole file (or program) | gst_rate |
| Translation unit | One .c file after preprocessing: what the compiler compiles at a time |
main.c + pasted headers |
| Separate compilation | Compiling each .c on its own, then linking |
gcc -c main.c |
make |
A tool that runs build commands and rebuilds only what changed | make |
| Makefile | The file of rules make reads: target, dependencies, Tab + command |
app: main.o bill.o |
| Target | What a Makefile rule builds | app, main.o |
| Dependency | A file a target is built from; if it changes, the target is rebuilt | bill.h |
-Wall |
gcc option that turns on the most useful warnings | gcc -Wall main.c bill.c |
| Encapsulation | Hiding data behind functions so other code can't change it directly | static int count in counter.c |
Summary
- One giant file doesn't scale: split the program into one
.cfile per job, and build them together:gcc main.c bill.c -o app. - The compiler works on one file at a time. A function used in another file needs a declaration (prototype); without one C guesses
intand you can get wrong answers. - Put the declarations in a header file and
#include "bill.h"everywhere it's needed, including inbill.citself. Quotes for your headers, angle brackets for the system's. #includeis copy-paste, so every header needs an include guard (#ifndef/#define/#endif) or#pragma once.- Headers hold declarations only. A shared global is
externin the header and defined once in a.c.statickeeps a function or global private to its file. gcc -cmakes object files; linking joins them. Rebuild only what changed, and letmakeremember the commands.
Next episode: Debugging with gdb: freeze a program on any line, step through it, look inside every variable, and find a crash in four commands.