Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make: *** No rule to make target `main.c', needed by `main.o'. Stop

Tags:

c

unix

gnu-make

functions.h

#include<stdio.h>
void print_hello(void);
int factorial(int n);

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>
int factorial(int n)
{
 if(n!=1)
 {
  return(n*factorial(n-1));
 }
 else
  return 1;
}

makefile

exec : \
 compile  
    echo "Executing the object file"
    ./compile 

compile : main.o hello.o factorial.o
    echo "Compiling"
    gcc -o compile $^

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

hello.o : hello.c functions.h
    gcc -c hello.c -I./INCLUDE -I./SRC

factorial.o : factorial.c functions.h
    gcc -c factorial.c -I./INCLUDE -I./SRC

Folder: make_example\INCLUDE\functions.h Folder: make_example\SRC\main.c Folder: make_example\SRC\hello.c Folder: make_example\SRC\factorial.c Folder: make_example\makefile

I'm getting an error when compiled the make file as "desktop:~/make_example$ make

make: * No rule to make target main.c', needed bymain.o'. Stop."

Please help me understand why this error

like image 552
Angus Avatar asked Jan 19 '12 12:01

Angus


2 Answers

When you run make it tries to make the first target in the file (exec), which depends on compile, which depends on main.o, which depends on main.c. There is no file main.c, only SRC/main.c. There is no rule to make a file called main.c, and there is no pre-existing main.c, so make has an error and exits.

You can fix this with VPATH or vpath:

VPATH = SRC INCLUDE 
like image 156
thiton Avatar answered Oct 10 '22 22:10

thiton


Your main.c is in the subdirectory src, and make does not know to look there. There are many options, the easiest of which is to write "src/main.c" instead of "main.c" in the makefile. You could also move main.c up a level, or move the makefile to src/ and build there, or put a makefile in the toplevel that cds into src and calls that make (this is recursive make, which many consider "harmful", but is perfectly fine in many(most) cases.) You can also use a VPATH directive, but if you choose to do so, be aware that this will not work with all versions of make.

like image 41
William Pursell Avatar answered Oct 10 '22 23:10

William Pursell