简体   繁体   中英

Working with makefile and subdirectories

I'm trying to figure out how to use makefile and subdirectories. But unluck till now. I want to put all the .o files in an "build" subdirecotry, all the .cpp should be in an "src" and the executable file in an "bin" file.

And this makefile was my attempt:

PROG = prog1
BINPATH = bin/
CC = g++
CPPFLAGS = -Wall -pedantic -ansi -Iinclude
OBJS = main.o calc.o show.o
BUILDPATH = build/
SRCPATH = src/$(PROG):$(BUILDPATH)$(OBJS)
$(CC) -o $(BINPATH)$(PROG) $(BUILDPATH)$(OBJS)
$(BUILDPATH)main.o:
    $(CC) $(CPPFLAGS) -c $(SRCPATH)main.cpp
$(BUILDPATH)cacula.o:calc.h
    $(CC) $(CPPFLAGS) -c $(SRCPATH)calc.cpp
$(BUILDPATH)show.o:show.h
    $(CC) $(CPPFLAGS) -c $(SRCPATH)show.cpp
clean:
    rm -f core $(BINPATH)$(PROG) $(BUILDPATH)$(OBJS)

The most immedite problem is that you are manipulating the variables wrong.

OBJS = main.o calc.o show.o
BUILDPATH = build/

So far, so good, but $(BUILDPATH)$(OBJS) will expand to build/main.o calc.o show.o , which is not what you want. Try this:

OBJS := main.o calc.o show.o
BUILDPATH := build/
OBJS := $(addprefix $(BUILDPATH), $(OBJS))

Then you can use OBJS like this:

$(PROG): $(OBJS)
    $(CC) -o $(BINPATH)$(PROG) $(OBJS)

There are several other ways to improve this makefile, but this should be enough to get it working.

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