简体   繁体   English

使用makefile和子目录

[英]Working with makefile and subdirectories

I'm trying to figure out how to use makefile and subdirectories. 我试图弄清楚如何使用makefile和子目录。 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. 我想将所有.o文件放在“ build”子目录中,所有.cpp文件应放在“ src”文件中,而可执行文件放在“ bin”文件中。

And this makefile was my attempt: 而这个makefile是我的尝试:

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. 到目前为止, $(BUILDPATH)$(OBJS)不错,但是$(BUILDPATH)$(OBJS)将扩展到build/main.o calc.o show.o ,这不是您想要的。 Try this: 尝试这个:

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

Then you can use OBJS like this: 然后,您可以像这样使用OBJS

$(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. 还有其他几种方法可以改善此makefile,但这足以使它正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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