Automate Your Builds with Make: Understanding Makefiles and Compilation Processes
110 likes | 259 Vues
Make is a powerful utility that streamlines the compilation of your programs by automatically managing dependencies and recompilation. By utilizing a Makefile (or makefile) in your directory, Make defines the relationships between files, detailing how to create targets from sources. This guide walks you through a simple example and a more complex scenario involving multiple source files, headers, and targets, highlighting key aspects of writing effective Makefiles. Whether you’re developing small or extensive projects, Make simplifies your build process.
Automate Your Builds with Make: Understanding Makefiles and Compilation Processes
E N D
Presentation Transcript
Make • Make is a system utility that automatically compiles your programs for you • Make looks for a file named Makefile (or makefile) in the current directory • Describes the relationships among files that comprise you program • Gives the commands for updating each file • Using the Makefile, make automatically: • Determines which files need to be recompiled • Issues the commands to recompile them
A Simple Program // hello.cpp #include <iostream> #include “hello.h” using namespace std; int main() { cout << MESSAGE << endl; }
The Header File // hello.h #define MESSAGE "Hello World!"
Compiling and Running the Program • Compiling: • g++ -O2 -o hello hello.cpp • Running • ./hello • Result: • Hello World!
Makefile • Composed of: • Comments (from a pound sign to the end of a line) # This is a comment • Macros – just like in your program CFLAGS= -O2 • Targets – lists dependencies and rules for updating hello: hello
The Makefile # Makefile for hello.cpp CFLAGS = -O2 hello: hello.h hello.cpp g++ $(CFLAGS) -o hello hello.cpp
Compiling and Running the Program with Make • Compiling: • make • Running • ./hello • Result: • Hello World! • Note: make is really unnecessary for such a simple program, but is essential for programs with lots of source files
Make - Pitfalls • Make is very picky about some things: • Indenting must be done with tabs not spaces • Dependencies must be correct • If nothing has changed make will tell you the target is “up to date”
A More Complicated Example • 5 source files • Some shared header files • Multiple targets • Make creates the first target by default • E.g. make • You can specify others: • E,g, make clean
Let’s Write a Makefile • 3 header files • src1.h – used by src1.cpp • src2.h – used by src2.cpp • global.h – used by src1.cpp, src2.cpp, and main.cpp • 4 source files • src1.cpp – routines used by main.cpp • src2.cpp – routines used by main.cpp • src3.cpp – routines used by src2.cpp • main.cpp – main program
Questions • What will make do if we touch: • global.h? • src1.h? • src2.h? • src3.cpp? • main.cpp?