I just wanted to write a quick Makefile for a small C++ project, but when I try to build, make says:
No rule to make target "obj/main.o"
even though my implicit rule should cover that file. I have seen others who had forgotten a slash or something, but I dont't see the problem with this Makefile:
.PHONY: run, clean
SRCDIR:=./src
OBJDIR:=./obj
BINDIR:=./bin
CC:=gcc
CXX:=g++
SRC:=$(shell find -name *.cpp)
HXX:=$(shell find -name *.hpp)
OBJ:=$(subst src/,obj/,$(SRC:%.cpp=%.o))
EXE:=main
CXXFLAGS:=-std=c++14 -Wall
$(EXE): $(OBJ)
@echo $(OBJ)
$(CXX) $(CXXFLAGS) $^ -o $(BINDIR)/$@
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(SRCDIR)/%.hpp
$(CXX) $(CXXFLAGS) -c $< -o $@
I am using Raspberry Pi OS on my Raspberry Pi 3 b.
because of
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(SRCDIR)/%.hpp
you can only compile file having both a cpp and a hpp , but your main does not have header (eg you have a src/main.cpp but no src/main.hpp )
Example:
pi@raspberrypi:/tmp/p $ find .
.
./bin
./src
./src/main.cpp
./Makefile
./obj
pi@raspberrypi:/tmp/p $ make
make: *** Aucune règle pour fabriquer la cible « obj/main.o », nécessaire pour « main ». Arrêt.
pi@raspberrypi:/tmp/p $ touch src/main.hpp
pi@raspberrypi:/tmp/p $ make
g++ -std=c++14 -Wall -c src/main.cpp -o obj/main.o
./obj/main.o
g++ -std=c++14 -Wall obj/main.o -o ./bin/main
pi@raspberrypi:/tmp/p $
( Aucune règle pour fabriquer la cible... means No rule to make target )
Changing the line by
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp
the compilation is done:
pi@raspberrypi:/tmp/p $ find .
.generally
./bin
./src
./src/main.cpp
./Makefile
./obj
pi@raspberrypi:/tmp/p $ make
g++ -std=c++14 -Wall -c src/main.cpp -o obj/main.o
./obj/main.o
g++ -std=c++14 -Wall obj/main.o -o ./bin/main
pi@raspberrypi:/tmp/p $
To add the dependency to the header is not enough to recompile when necessary when a source #include
other header files which is often the case.
You can look at makedepend , to install it under raspbian/debian/ubuntu: apt-get install xutils-dev
Note the link is done each time you do make :
pi@raspberrypi:/tmp/p $ find .
.
./bin
./bin/main
./src
./src/main.hpp
./src/main.cpp
./Makefile
./obj
./obj/main.o
pi@raspberrypi:/tmp/p $ make
./obj/main.o
g++ -std=c++14 -Wall obj/main.o -o ./bin/main
pi@raspberrypi:/tmp/p $ make
./obj/main.o
g++ -std=c++14 -Wall obj/main.o -o ./bin/main
pi@raspberrypi:/tmp/p $
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.