简体   繁体   中英

Makefile on different folders

I know it has already been discussed a lot, but I'm getting a bit crazy and cannot figured it out by myself.

I'm trying to learn how to create makefiles, and I'm having problems in defining a makefile for files in different folders.

This is what I would like to obtain, after compiling:

/makefile
/test.exe
/src/factorials.cpp
/src/main.cpp
/src/hello.cpp
/obj/factorials.o
/obj/main.o
/obj/hello.o
/include/functions.h

What is wrong with this makefile?

C++ = g++
FILENAME = test
SOURCES_PATH = src/
SRC = $(SOURCES_PATH)factorial.cpp $(SOURCES_PATH)main.cpp $(SOURCES_PATH)hello.cpp
OBJ = factorial.o main.o hello.o

all: test.exe

test.exe: $(OBJ)
$(C++) $(OBJ) -o $(FILENAME) -Iinclude

%.o: 
$(C++) -c $(SOURCES_PATH)$*.cpp -Iinclude

clean:
rm -f test.exe

Everything goes correctly, but it gives me error trying to compile src/all.cpp . Besides, I don't know how to say to g++ to put .o files into obj/ folder.

Thanks a lot!

You should fix your .o rule as follows

obj/%.o: $(SOURCES_PATH)/%.cpp
    $(CC) $(CXXFLAGS) $< -o $@

Alternatively $(vpath) can be used to resolve where make looks up the source (prerequisite) files for a target:

vpath += $(SOURCES_PATH)

obj/%.o: %.cpp
    $(CC) $(CXXFLAGS) $< -o $@

So it seems I was able to obtain the result by using the following makefile

C++ = g++
FILENAME = test
OBJS = obj/factorial.o obj/hello.o obj/main.o
INC = -Iinclude/
vpath+= src

$(FILENAME): $(OBJS)
    $(C++) $(OBJS) -o $@ $(INC)

obj/%.o: %.cpp
    $(C++) -o $@ -c $< $(INC)

all: $(FILENAME)

clean:
    rm -rf objs/*.o *~ $(FILENAME).exe

Thanks! :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM