Makefile,在src目录树中找到源,并在构建文件中编译为.o [英] Makefile, find sources in src directory tree and compile to .o in build file

查看:199
本文介绍了Makefile,在src目录树中找到源,并在构建文件中编译为.o的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试为继承的项目重新编写一个makefile,以使源代码树更加整洁并易于使用.目前,源代码树是这样的:

I'm currently trying to re-write a makefile for a project that I've inherited to make the source tree neater and easier to work with. At the moment the source tree is something like this:

 Project/
 ----bin/
 ----build/
 ----include/
     ----main.h
     ----part1.h
     ----part2.h
     ----part3.h
 ----src/
     ----main.cpp
     ----part1.cpp
     ----Subdir/
         ----part2.c
     ----Subdir2/
         ----part3.cpp

我想要的是我的makefile中的一条规则,该规则将在我的src目录中找到所有.cpp和.c文件,并将它们编译为build目录中的平面对象目录.目前,我的makefile文件中包含以下内容,但这似乎错过了许多cpp文件:

What I want is a rule in my makefile that will find all of the .cpp and .c files in my src directory and compile them to a flat directory of objects in the build directory. At the moment I have the following in my makefile but this seems to miss a number of the cpp files:

BUILDDIR = build

$(BUILDDIR)/%.o :       src/**/%.cpp | $(BUILDDIR)
$(BUILDDIR)/%.o :       src/%.cpp    | $(BUILDDIR)
    $(CXX) $(CFLAGS) -c $< -o $@ $(INCS)

$(BUILDDIR)/%.o :       src/**/%.c   | $(BUILDDIR)
$(BUILDDIR)/%.o :       src/%.c      | $(BUILDDIR)
    $(CC)  $(CFLAGS) -c $< -o $@ $(INCS)

在我运行make -n的那一刻,它似乎已检测到main.cpp和part1.cpp,但在子目录中均未检测到.然后,Make继续尝试根据Makefile中的后续规则加载文件.

At the moment when I run make -n it seems that it has detected main.cpp and part1.cpp but none of the ones in subdirectories. Make then goes on to try and load the files according to later rules in the Makefile.

由于项目中文件的数量,我宁愿不手动编写文件列表,但如果涉及到这一点,我可能不得不这样做.

Due to the number of files in the project I'd rather not write a list of them manually but if it comes to that I might have to.

推荐答案

您可以显式定义带有源文件的目录.例如:

You can explicitly define directories with source files. For example:

DIRS = src src/subdir1 src/subdir2
SEARCHC = $(addsuffix /*.c ,$(DIRS))
SEARCHCPP = $(addsuffix /*.cpp ,$(DIRS))
SRCS = $(wildcard $(SEARCHC))
SRCS += $(wildcard $(SEARCHCPP))

并让make查找您的源文件添加到您的Makefile中:

And to let make find your sources files add to your Makefile:

vpath %.c $(DIRS)
vpath %.cpp $(DIRS)

我还使用特殊目标来检查我的Makefile:

I am also using special target to check my Makefile:

help:
    @echo 'Sources:'
    @echo $(SRCS)

这篇关于Makefile,在src目录树中找到源,并在构建文件中编译为.o的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆