简体   繁体   中英

Makefile, find sources in src directory tree and compile to .o in build file

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

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)

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))

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

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

I am also using special target to check my Makefile:

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

Make's wildcard function could be of use to you here.

See also

Sources from subdirectories in Makefile

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