Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile: Compiling from directory to another directory

Tags:

makefile

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.

like image 461
user1777907 Avatar asked Jun 04 '13 17:06

user1777907


People also ask

How do I run a makefile in another directory?

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.

Should makefile be in src directory?

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.

How do I run a makefile with a different name?

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.


1 Answers

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)
like image 129
MadScientist Avatar answered Dec 09 '22 07:12

MadScientist