So, from previous tutorials, you are now confident in compiling: given code.c
, you can quickly obtain anexecutable
and run the file. Now, what if your code base grows, incurring multiple source files, header files and libraries? Managing them could be troublesome, if possible at all. That is where Makefile
will save your day. But before diving into Makefile
, let us first c the presence of multiple source and header files.
Create a directory for our code with
mkdir -p ~/make_tut/tut_2 && cd ~/make_tut/tut_2
Create 5 pieces of code hello_make.c
, func_1.h
, func_2.h, func_1.c
and func_2.c
as following
//hello_make.c
#include <func_1.h>
#include <func_2.h>
int main(){
func_1();
func_2();
return 0;
}
//func_1.h
#include <stdio.h>
void func_1();
//func_2.h
#include <stdio.h>
void func_2();
//func_1.c
#include <func_1.h>
void func_1(){
printf("Hello make!");
}
//func_2.c
#include <func_2.h>
void func_2(){
printf("I am feeling good!")
}
You might already guessed that hello_make.c
has to depend on func_1.c
and func_2.c
. Therefore we will need to obtain func_1.o
and func_2.o
, and then link them to obtain hello_make.o
and its executable. Let's try the naive way:
gcc -c func_1.c -o func_1.o
Unfortunately, get an error like this
func_1.c:1:20: fatal error: func_1.h: No such file or directory
compilation terminated.
That is because we did not instruct the gcc compiler where to look for our header file func_1.h
. This was not necessary for stdio.h
because it is a system library. In stead, the right command would be
gcc -c func_1.c -o func_1.o -I .
gcc -c func_2.c -o func_2.o -I .
gcc -c hello_make.c -o hello_make.o -I .
where -I
stands for "include directories", and .
stands for current directory (in Linux), not the end of sentence. Upon this command you will get three pieces of machine code func_1.o
, func_2.o
and hello_make.o
.
Now to get the final executable, just issue this command
gcc hello_world.o func_1.o func_2.o -o hello_make
And voilà, you have just manually compiled an executable from multiple piece of code!
But then if you have a hundred pieces of code files, the amount of typing could be a problem...