I am trying to use Makefile to compile a bunch of .cpp
files located in src/code/*.cpp
, then compile each *.o
in build/
, and finally generate executable with those in build/
as well.
I have read a couple answers that I tried to work with but have encountered issues 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 do get the following error, and I am not sure why:
Makefile:19: target `src/code/main.cpp' doesn't match the target pattern
I also see that when trying to build the EXECUTABLE, it is not using the .o files, so it seems my rule is wrong here.
Use cd ./dir && make && pwd inside Makefile . The && was exactly what I needed to change a directory and execute a command there, then drop back to the main folder to finish the build.
Since these files normally appear in the source directory, they should always appear in the source directory, not in the build directory. So Makefile rules to update them should put the updated files in the source directory.
If you want to use a nonstandard name for your makefile, you can specify the makefile name with the ' -f ' or ' --file ' option. The arguments ' -f name ' or ' --file= name ' tell make to read the file name as the makefile.
Your patsubst
function is wrong; you can't use shell wildcard characters like *
. You want:
OBJECTS = $(patsubst $(SOURCEDIR)/%.cpp,$(BUILDDIR)/%.o,$(SOURCES))
Also you should be using SOURCEDIR
and BUILDDIR
everywhere, not just in some places (otherwise you'll get inconsistencies). And finally, your SOURCEDIR value is wrong: it should not start with /
I expect:
SOURCEDIR = src/code
SOURCES = $(wildcard $(SOURCEDIR)/*.cpp)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With