My C file is too big! Multifile source compilation
In this basic example, we will see how to use a header file, compile two source files into one executable, and separate a C program into its component parts using gcc.
File Structure:
main.c: The main source file.functions.c: A source file containing additional functions.functions.h: A header file containing function declarations.
functions.h:
// functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
// Function declaration
void print_hello();
#endif // FUNCTIONS_H
functions.c:
// functions.c
#include "functions.h"
#include <stdio.h>
// Function definition
void print_hello() {
printf("Hello, World!\n");
}
main.c:
// main.c
#include "functions.h"
int main() {
// Call function from another file
print_hello();
return 0;
}
Compilation Steps:
Compile
functions.cinto an object file:gcc -c functions.c -o functions.oThis command compiles
functions.cinto an object filefunctions.owithout linking.Compile
main.cinto an object file:gcc -c main.c -o main.oThis command compiles
main.cinto an object filemain.owithout linking.Link the object files into a single executable:
gcc main.o functions.o -o myprogramThis command links
main.oandfunctions.otogether to create the final executablemyprogram.
After these steps, you will have an executable file named myprogram that you can run on your system. To execute the program, use:
./myprogram
This will output:
Hello, World!
This is only a basic example; in practice, your program's complexity will determine the number of source and header files you require, as well as whether or not you need to link with other libraries or include additional compiler options.