简体   繁体   中英

[MAKEFILE]: How to copy cpp source files from different source folders into one destination folder and use those cpp files to build using MAKE

My Current makefile looks like the following, and it build the targets correctly. But it fails to build the targets in one instance, that is when the length of the path to source files becomes too long. Therefore I want to collect all my source files in different folders into one single source directory and then do the make.

Any leads on how I can modify the following makefile to create a flat source directory and use the files in that directory to build using make

PROJ_DIR := ../
SRC_DIR += $(PROJ_DIR)project
SRC_FILES += $(wildcard $(SRC_DIR)/*/source/*.cpp)
OBJ_DIR := $(PROJ_DIR)TASK
OBJ_FILES += $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))

CXXFLAGS := --c++14

CC_INCLUDE_PATH += -I$(PROJ_DIR)project/include

.PHONY: all clean dirs

all: $(OBJ_DIR) $(OBJ_FILES) 
    "$(COMPILERBIN)"/cc.exe -rvn crackLib.a $(OBJ_FILES)

clean:
    @rm -rf crackLib.a $(OBJ_DIR) $(FLAT_INC_DIR)  

# Build target for directory creation. Intermediate build files will be placed here.
$(OBJ_DIR):
    mkdir -p $@

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp 
    "$(COMPILERBIN)"/cc.exe $(CXXFLAGS) -c -o $@ $< $(CC_INCLUDE_PATH) 

$(OBJ_DIR)/%.o: $(TSM_SRC_DIR)/%.cpp
    "$(COMPILERBIN)"/cc.exe $(CXXFLAGS) -c -o $@ $< $(CC_INCLUDE_PATH) 

$(OBJ_DIR)/%.o: $(SL_SRC_DIR)/%.cpp
    "$(COMPILERBIN)"/cc.exe $(CXXFLAGS) -c -o $@ $< $(CC_INCLUDE_PATH) 

-include $(OBJ_FILES:.o=.d)

Suppose we have the source file $(SRC_DIR)/longpath/source/foo.cpp , and we want to build the object file $(OBJ_DIR)/foo.o . We might wish for this rule:

$(OBJ_DIR)/foo.o: $(SRC_DIR)/longpath/source/foo.cpp
    ... $< -o $@

But we don't know the path when we write the makefile, so we must ask Make to figure it out at build time.

There is more than one way to do this. The simplest is to use the vpath directive .

If we ken the path ahead of time, we could write this:

vpath %.cpp $(SRC_DIR)/longpath/source

$(OBJ_DIR)/foo.o: foo.cpp
    ... $< -o $@

Make would use vpath to search for the source file, and use its full path as the prerequisite (and therefore $< ).

The vpath directive can take multiple directories, and although we don't know the path beforehand, we know how to compute them:

vpath %.cpp $(dir $(SRC_FILES))

$(OBJ_DIR)/foo.o: foo.cpp
    ... $< -o $@

And once we confirm that this works, we can switch to a pattern rule:

$(OBJ_DIR)/%.o: %.cpp
    ... $< -o $@

and change OBJ_FILES accordingly:

OBJ_FILES += $(patsubst %.cpp,$(OBJ_DIR)/%.o,$(notdir $(SRC_FILES)))

all: $(OBJ_FILES)
    ... $^

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