简体   繁体   中英

Single top-level makefile with source subdirectories

Firstly, apologies for my ignorance. I'm sure the answer to my question exists in one of the many existing makefile threads here. However, I have been unable to find one that concisely and clearly answers my specific question without obfuscating the answer with details that aren't relevant to my particular situation.

My code directory has a single top-level source file containing main. The rest of the source files are organised in subdirectories according to logical divisions in the system. The code contains no relative paths in the includes. This means that everything works perfectly if all the code is in a single directory using the following, simple makefile:

CC=g++
CFLAGS=-c
LDFLAGS=
SOURCES=Main.cpp Source1.cpp Source2.cpp Source3.cpp Etc.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=executable

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS) 
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@

Until now I have been building my code using the NetBeans IDE. This has helped preserve my make ignorance by generating some vast and overly complicated makefiles on my behalf. Now the time has come to distribute my code for public use so I'm looking to produce a makefile will enable me to distribute the code with the directory structure I have.

Can you help?

Regards, Enthusastic Amateur.

Take a look at this:

# Source directories separated by space
# Example ./ src1/ src2/
SRCDIR   = ./ src/
# Directory where object files will be placed
OBJDIR   = obj/
# Include directories separated by space
# Example: include1/ include2/
INCDIR   = include/
# Directory where binary file will be placed
BINDIR   = bin/
# Name of the result file
TARGET   = app
# Compiler
CXX      = g++

# Retrive list of the source files
SRC      = $(wildcard $(addsuffix *.cpp,$(SRCDIR)))
# Generate list of the object files
OBJ      = $(addprefix $(OBJDIR), $(patsubst %.cpp, %.o, $(notdir $(SRC))))

VPATH    = $(SRCDIR)

# Compilation flags
CXXFLAGS = -std=c++11 -pthread

$(TARGET) : $(OBJ)
    @echo Linking...
    @mkdir -p $(BINDIR)
    @$(CXX) $(CXXFLAGS) -o $(BINDIR)$@ $(OBJ)

$(OBJDIR)%.o : %.cpp
    @echo Compiling $< in $@...
    @mkdir -p $(OBJDIR)
    @$(CXX) $(CXXFLAGS) $(addprefix -I,$(INCDIR)) -c -o $@ $<

clean :
    @$(RM) -r $(OBJDIR)
    @$(RM) -r $(BINDIR)

Here you can provide multiple source directories.

And "everything works perfectly" as well if the code is in multiple directories, using the same makefile you already have. No changes needed.

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