0
votes

I have a small project with the files in src folder: functionAdd.cpp; functionSubtract.cpp; main.cpp and my Makefile. In include folder i got functionAdd.hpp and functionSubtract.hpp. First i had an error like, can't find these two .hpp file. After referencing to this answer i made new Makefile. so here what i did:

CC = g++
HEADER1 = home/administrator/Desktop/makefile-test/include/functionAdd.hpp
HEADER2 = home/administrator/Desktop/makefile-test/include/functionSubtract.hpp
CFLAGS = -c -Wall -Iinclude

all:calculation

calculation: main.o functionSubtract.o functionAdd.o
        $(CC) main.o functionSubtract.o functionAdd.o -o calculation

main.o: main.cpp  $(HEADER) $(HEADER2)
        $(CC) $(CFLAGS) main.cpp

functionSubtract.o: functionSubtract.cpp $(HEADER2)
        $(CC) $(CFLAGS) functionSubtract.cpp

functionAdd.o: functionAdd.cpp $(HEADER1)
        $(CC) $(CFLAGS) functionAdd.cpp

clean:
        rm -rf *o calculation  

Now the error message is: make: *** No rule to make target home/administrator/Desktop/makefile-test/include/functionSubtract.hpp, needed by main.o. Stop.

1
Add / on front of the home/... paths: /home/.... Are src and include subdirectories of the same parent directory? If yes there are simpler solutions than specifying the absolute paths.Renaud Pacalet
@RenaudPacalet Yes they are subdirectories of the same parent directory. Even though i fixed my problem yet, still interesting to see your simpler solution that u mentioned.casper

1 Answers

0
votes

Assuming the source files, header files and Makefile are organized like this:

src/Makefile
src/*.cpp
include/*.hpp

Then you could use:

  • relative paths instead of absolute (more portable, less error prone, less typing),
  • make automatic variables (more generic, less error prone, less typing),
  • make pattern rules.
CC = g++
HEADER1 = ../include/functionAdd.hpp
HEADER2 = ../include/functionSubtract.hpp
CFLAGS = -c -Wall -I../include

.PHONY: all clean

all: calculation

calculation: main.o functionSubtract.o functionAdd.o
        $(CC) $^ -o $@

%.o: %.cpp
    $(CC) $(CFLAGS) $< -o $@

main.o: $(HEADER) $(HEADER2)
functionSubtract.o: $(HEADER2)
functionAdd.o: $(HEADER1)

clean:
        rm -rf *o calculation

Slightly more compact and easier to maintain.