Makefile Beginner Study Notes
🚧 Under Construction
Learning source: 20-Minute Lightning Fast Makefile Tutorial By: GeekHour
Recommendation: ⭐⭐⭐⭐
Build
Definition
\\{ \\text{Source files, resource files} \\} \\rightarrow \\text{Executable file}
Process
\\{ \\text{Source file} \\} \\rightarrow \\{ \\text{Preprocessing} \\} \\rightarrow \\{ \\text{Compilation} \\} \\rightarrow \\{ \\text{Assembly} \\} \\rightarrow \\{ \\text{Linking} \\} \\rightarrow \\{ \\text{Packaging/Deployment} \\}
How to build
- For a single file, we can directly use a compilation command to build the program.
- For multiple source files and resources, using an automated build system is a better choice.
Learning Make
Repository: Code Repo
Compiling and Running Source Files with Commands
Create a file main.c with a simple C program:
#include <stdio.h>
int main(){
printf("Hello, World!\n");
return 0;
}
In the shell[1], enter:
gcc main.c -o hello
This uses GCC[2] to compile main.c into an executable.
Run with:
./hello
Simple Usage of Make
- Create a header file
message.h
void message();
- Create
message.c
#include <stdio.h>
void message() {
printf("Hello, World!\n");
}
- Modify
main.c
#include <stdio.h>
#include "message.h"
int main(){
+ message();
- printf("Hello, World!\n");
return 0;
}
- Add a
Makefile
hello: main.c message.c
gcc main.c message.c -o hello
Make Best Practices
1. Step-by-step compilation
hello: main.o message.o
gcc main.o message.o -o hello
main.o: main.c
gcc -c main.c
message.o: message.c
gcc -c message.c
Advantage: If only message.c is modified, then main.c will not be recompiled.
2. Phony targets
clean:
rm -f *.o hello
Note: There must not be an actual file with the same name as the phony target.
[1] The author uses Windows 11; here "Shell" generally refers to the Command Prompt. See Microsoft official support.
[2] For installing GCC, see FreeCodeCamp - How to Install C and C++ Compilers on Windows.