Home > database >  Add a source directory to a Makefile
Add a source directory to a Makefile

Time:07-19

I have the following makefile:

CPP_COMPILER = g  
CPP_COMPILER_FLAGS = -g -O0 -Wall -Wextra -Wpedantic -Wconversion -std=c  17
EXECUTABLE_NAME = mainDebug

CPP_COMPILER_CALL = $(CPP_COMPILER) $(CPP_COMPILER_FLAGS)

INCLUDE_DIR = include
SOURCE_DIR = src1
BUILD_DIR = build

CPP_SOURCES = $(wildcard $(SOURCE_DIR)/*.cpp)
CPP_OBJECTS = $(patsubst $(SOURCE_DIR)/%.cpp, $(BUILD_DIR)/%.o, $(CPP_SOURCES))

build: $(BUILD_DIR)/$(EXECUTABLE_NAME)

TARGET_DEPS = $(CPP_OBJECTS)
$(BUILD_DIR)/$(EXECUTABLE_NAME): $(TARGET_DEPS)
    $(CPP_COMPILER_CALL) $^ -o $@

execute:
    .$(BUILD_DIR)/$(EXECUTABLE_NAME)

$(BUILD_DIR)/%.o: $(SOURCE_DIR)/%.cpp
    $(CPP_COMPILER_CALL) -I $(INCLUDE_DIR) -c $< -o $@

clean:
    rm -rf $(BUILD_DIR)/*.o $(BUILD_DIR)/$(EXECUTABLE_NAME)

And the following folder structure:

.
├── build
├── include
│   ├── mylib.h
│   └── test.h
├── Makefile
├── src1
│   ├── main.cc
│   └── mylib.cc
└── src2
    └── test.cc

This works correctly with src1 but when adding src2 to SOURCE_DIR,

SOURCE_DIR =    src1\
                src2

I get the following error:

/usr/bin/ld: cannot find src1: file format not recognized
collect2: error: ld returned 1 exit status
make: *** [Makefile:22: build/mainDebug] Error 1

What am I doing wrong here ?

CodePudding user response:

Look at how you use SOURCE_DIR:

SOURCE_DIR = src1
...
CPP_SOURCES = $(wildcard $(SOURCE_DIR)/*.cpp)
CPP_OBJECTS = $(patsubst $(SOURCE_DIR)/%.cpp, $(BUILD_DIR)/%.o, $(CPP_SOURCES))
...
$(BUILD_DIR)/%.o: $(SOURCE_DIR)/%.cpp
    $(CPP_COMPILER_CALL) -I $(INCLUDE_DIR) -c $< -o $@

After you define it, you use it three times, each time as a single directory name. You cannot simply add a second name to the variable and expect Make to iterate properly over the list.

First, use addsuffix to get the right pattern for wildcard:

CPP_SOURCES = $(wildcard $(addsuffix /*.cpp,$(SOURCE_DIR)))

Then use CPP_SOURCES instead of SOURCE_DIR:

CPP_OBJECTS = $(patsubst %.cpp, $(BUILD_DIR)/%.o, $(notdir $(CPP_SOURCES)))

Then use vpath to find the sources:

vpath %.cpp $(SOURCE_DIR)
$(BUILD_DIR)/%.o: %.cpp
    $(CPP_COMPILER_CALL) -I $(INCLUDE_DIR) -c $< -o $@
  • Related