简体   繁体   中英

Getting compilation error with makefile

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.

Replace

#include<functions.h>

with

#include"functions.h"

A detailed explanation is here: http://www.geekinterview.com/question_details/3379

And finally, object files are missing at the linking stage.

compile : main.o hello.o factorial.o
  gcc -o compile main.o hello.o factorial.o

Alternative to changing the source, you can include the current directory for header file lookup using -I option of gcc. In that case your makefile rule where you need the header file will look like as follows (assuming the header file is the current directory):

main.o : main.c functions.h
  gcc -c main.c -I./

Again as already pointed out, the error you were facing later during linking was due to missing input files in the compile target. For this again there is alternative. You can make use of $^ in the makefile for all you depencies. In which you compile rule will look like:

compile:main.o hello.o factorial.o
    gcc -o compile $^

See this link for some information regarding makefile macros.
Side notes:

  1. Guards are missing your header file
  2. There is mismatch in declaration & definition of factorial function.
  3. As already mentioned by Jonathan Leffler be adviced about the prototype of print_hello

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM