How to generate object files in the build directory?
I am currently working on a C project to implement a Linux userspace application. I wrote this Makefile, which allows me to compile :
PROJ_DIR := ../
SRC_DIR := $(PROJ_DIR)/src
BUILD_DIR := $(PROJ_DIR)/build
# define the executable file
TARGET := tcp_proxy
# include paths list
INC_DIRS := $(SRC_DIR)
INC_DIRS += $(SRC_DIR)/rpmsg
INC_DIRS += $(SRC_DIR)/rpmsg/rx
INC_DIRS += $(SRC_DIR)/rpmsg/tx
INC_DIRS += $(SRC_DIR)/tcp
INC_DIRS += $(SRC_DIR)/tcp/rx
INC_DIRS += $(SRC_DIR)/tcp/tx
INC_FLAGS := $(addprefix -I,$(INC_DIRS))
# source file list
SRCS := $(shell find $(SRC_DIR) -name *.c)
# object file list
OBJS := $(SRCS:.c=.o)
LDFLAGS := -pthread
all: tcp_proxy
tcp_proxy: $(OBJS)
$(CC) $(CFLAGS) $(INC_FLAGS) -o $(TARGET) $(OBJS) $(LDFLAGS)
%.o: %.c
$(CC) $(CFLAGS) $(INC_FLAGS) -c $< -o $@
.PHONY: clean
clean:
$(RM) *.o *~ $(TARGET)
However, the object files are generated in the same place as the source files. So I would like to know how to duplicate the folders under "src" in a "build" directory and generate inside this directory the object files and the executable.
I would also like, when I do a make clean, to be able to delete all the object files and the executable.
My project :
Searching would definitely find you a lot of examples and information on this.
First tell make what objects you want to build; change your setting of OBJS
to this:
# object file list
OBJS := $(SRCS:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)
Then tell make how to build it; change your pattern rule for building objects to this:
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
@mkdir -p $(@D)
$(CC) $(CFLAGS) $(INC_FLAGS) -c $< -o $@