Makefile: compiling from a directory to another directory

I am trying to use a Makefile to compile bundles of .cpp files located in src/code/*.cpp , then compile each *.o in build/ and finally generate an executable file using in build/ .

I read a couple of answers that I tried to work with, but ran into problems that I do not understand.

 CC = g++ FLAGS = -g -c SOURCEDIR = /src/code BUILDDIR = build EXECUTABLE = DesktopSpecificController SOURCES = $(wildcard src/code/*.cpp) OBJECTS = $(patsubst src/code/*.cpp,build/%.o,$(SOURCES)) all: dir $(BUILDDIR)/$(EXECUTABLE) dir: mkdir -p $(BUILDDIR) $(BUILDDIR)/$(EXECUTABLE): $(OBJECTS) $(CC) $^ -o $@ $(OBJECTS): $(BUILDDIR)/%.o : $(SOURCEDIR)/%.cpp $(CC) $(FLAGS) $< -o $@ clean: rm -f $(BUILDDIR)/*o $(BUILDDIR)/$(EXECUTABLE) 

I get the following error, and I'm not sure why:

 Makefile:19: target `src/code/main.cpp' doesn't match the target pattern 

I also see that when I try to build EXECUTABLE it does not use .o files, so it seems my rule is wrong here.

+6
source share
1 answer

Your patsubst function is incorrect; you cannot use shell wildcards such as * . Do you want to:

 OBJECTS = $(patsubst $(SOURCEDIR)/%.cpp,$(BUILDDIR)/%.o,$(SOURCES)) 

You should also use SOURCEDIR and BUILDDIR everywhere, and not just in some places (otherwise you will get inconsistencies). And finally, your SOURCEDIR value is wrong: it should not start with / I expect:

 SOURCEDIR = src/code SOURCES = $(wildcard $(SOURCEDIR)/*.cpp) 
+8
source

Source: https://habr.com/ru/post/946525/


All Articles