I tried the following example program to understand the usage of the makefiles in compilation.
main.c
#include<stdio.h>
#include<functions.h>
int main()
{
print_hello();
printf("\nThe Factorial is : %d\n",factorial(5));
return 0;
}
hello.c
#include<stdio.h>
#include<functions.h>
void print_hello()
{
printf("\nHello world!\n");
}
factorial.c
#include<stdio.h>
#include<functions.h>
void factorial(int n)
{
if(n!=1){
return(n*factorial(n-1));
}
else
return 1;
}
functions.h
#include<stdio.h>
void print_hello();
int factorial(int n);
makefile
exec : ./compile
compile : main.o hello.o factorial.o
gcc -o compile
main.o : main.c functions.h
gcc -c main.c
hello.o : hello.c functions.h
gcc -c hello.c
factorial.o : factorial.c functions.h
gcc -c factorial.c
Error :
cheetah@desktop:~/make_example$ make compile gcc -c main.c main.c:2:22: error: functions.h: No such file or directory make: *** [main.o] Error 1 cheetah@desktop:~/make_example$
EDITED:
gcc -c main.c
gcc -c hello.c
gcc -c factorial.c
gcc -o compile
gcc: no input files
make: *** [compile] Error 1
Please help me understand why is it throwing an error as functions.h not found as I have included it in my makefile.
Alternative to changing the source, you can include the current directory for header file lookup using
-Ioption of gcc. In that case yourmakefilerule where you need the header file will look like as follows (assuming the header file is the current directory):Again as already pointed out, the error you were facing later during linking was due to missing input files in the
compiletarget. For this again there is alternative. You can make use of$^in the makefile for all you depencies. In which youcompilerule will look like:See this link for some information regarding makefile macros.
Side notes:
factorialfunction.print_helloHope this helps!