Abhijatya Singh
Abhijatya Singh

Reputation: 642

Object not found error make

I have the directory structure as src/ obj/ include/ bin/ I have created 2 .cpp file in src folder and a header file used by both cpp file in include folder. I want to create object file in obj folder and binary in bin folder below:

   vpath %.cpp src

   vpath %.h include

   vpath %.o obj

  all : main.o factorial.o run


  run : main.o factorial.o
      cc $^ -o bin/$@ -lstdc++ 

  main.o : main.cpp functions.h 
      cc -c $<  $(inc) -o obj/$@ -lstdc++

 factorial.o : factorial.cpp functions.h
      cc -c $<  $(inc) -o obj/$@ -lstdc++

 clean :
      rm -rf bin/* obj/*

and while making first time following is the output:

  betatest@dragon make-tut]$ make

     cc -c src/main.cpp  -I include -o obj/main.o -lstdc++

     cc -c src/factorial.cpp  -I include -o obj/factorial.o -lstdc++

     cc main.o factorial.o -o bin/run -lstdc++ 

     cc: main.o: No such file or directory

     cc: factorial.o: No such file or directory

     make: *** [run] Error 1

betatest@dragon make-tut]$

If i run make again then no error:

[betatest@dragon make-tut]$ make
cc obj/main.o obj/factorial.o -o bin/run -lstdc++ 

What is the problem?

Upvotes: 0

Views: 848

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80911

First rule of makefiles. Targets need to create a file with the exact name of the target.

So all your rules (e.g. main.o : main.cpp functions.h ; cc -c $< $(inc) -o obj/$@ -lstdc++) that generate files in a directory but do not include that directory in the target name are incorrect.

This causes the problem in the first run as make believes it has created factorial.o and main.o but it has actually created obj/factorial.o and obj/main.o.

The second run the vpath directives you have written are in play and make correctly finds the obj/factorial.o and obj/main.o objects under the bare factorial.o and main.o names.

Upvotes: 1

Related Questions