Compiling and Linking C Source Files in a Makefile
You aim to create a Makefile that compiles all C source files in the /src folder and links them into a binary in the root /project folder. Here's how you can achieve this:
Makefile Configuration
SRC_DIR := src OBJ_DIR := obj SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp) OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ... CPPFLAGS := ... CXXFLAGS := ...
main.exe: $(OBJ_FILES) g++ $(LDFLAGS) -o $@ $^
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
This Makefile will compile each source file in the /src directory into a corresponding .o file in the /obj directory. It will then link all the .o files to create the main.exe binary in the /project directory.
Best Practices
This approach is generally considered a common approach to compiling and linking C source files in a project. However, there are certain best practices to follow:
The above is the detailed content of How do I compile and link C source files into a binary using a Makefile?. For more information, please follow other related articles on the PHP Chinese website!