Concepts:
How to write a simple makefile
Text:
In the directory src
you can find in the file fz.c
the implementation of the function mul
that returns the results of the multiplication of two integer numbers:
#include "fz.h" int mul(int a, int b){ return a*b; }
In the directory inc
you can find in the file fz.h
the prototype of the function mul
:
#ifndef _FZ_H #define _FZ_H int mul(int a, int b); #endif
Finally, the main.c
file in the “.” directory makes use of the function mul
to obtain the result of the multiplication between numbers 2 and 4:
#include <stdio.h> #include <stdlib.h> #include "fz.h" int main(){ printf("%d\n", mul(2,4)); return EXIT_SUCCESS; }
Build a makefile
for the compilation of this program. In particular, the makefile
has to:
prog
clean
that removes all object files and the executable prog
install
that creates a directory bin
and copies the executable prog
in bin
distclean
that removes the directory bin
and its content, all object files and the executable prog
Example:
All files are compiled and the linker generates the executable prog
:
$ make gcc -Wall -I inc -g -c main.c gcc -Wall -I inc -g -c src/fz.c gcc -o prog main.o fz.o
Modifying one file, for example fz.c
with the command touch src/fz.c
, only the modified file is compiled:
$ touch src/fz.c $ make gcc -Wall -I inc -g -c src/fz.c gcc -o prog main.o fz.o
With make clean
, the files main.o
, fz.o
and prog
are deleted:
$ make clean rm -f main.o fz.o rm -f prog
With make install
the program is compiled and the executable prog
generated (this first step is performed only because the program prog
has been deleted in the previous step), then the directory bin
is created, and finally the file prog
is copied in the directory bin
:
$ make install gcc -Wall -I inc -g -c main.c gcc -Wall -I inc -g -c src/fz.c gcc -o prog main.o fz.o mkdir -p bin cp prog bin
With make distclean
the directory bin
and its content, all object files and the executable prog
are removed:
$ make distclean rm -f main.o fz.o rm -f prog rm -fr bin
Solution:
target: main.o fz.o gcc -o prog main.o fz.o main.o: main.c inc/fz.h gcc -Wall -I inc -g -c main.c fz.o: src/fz.c inc/fz.h gcc -Wall -I inc -g -c src/fz.c clean: rm -f main.o fz.o rm -f prog install: target mkdir -p bin cp prog bin distclean: clean rm -fr bin
DOWNLOAD COMPLETE EXAMPLE: makefile_1.zip
Comments: