如何在Makefile中移除文件扩展名?实际配置问题求助
Fixing Your Makefile Test Executable Generation Issue
Hey there! Let's break down what's going wrong with your current Makefile and get that test executable built correctly.
What's Causing the Problem?
Looking at your code, there are two key issues preventing your test file from generating as expected:
- Incorrect test file filtering: Your
TESTFILEvariable usespatsubst %_test.c,%,$(SRCFILES)which tries to apply the substitution to all source files. For files that don't end with_test.c, this substitution does nothing—soTESTFILEends up containing a mix of your test target and every other source file name (without extensions), which makes the build rule confused. - Duplicate
alltargets: You've definedalltwice. Make will only use the last definition, so your firstall: $(TESTFILE)was being ignored entirely.
Corrected Makefile
Here's the fixed version with explanations for the key changes:
CC=gcc CFLAGS=-c LDFLAGS= # Get all .c source files SRCFILES := $(shell find ../ -name '*.c') # Convert all .c files to .o object files OBJFILES := $(patsubst %.c,%.o,$(SRCFILES)) # FIRST: Filter only the test source files (ending with _test.c) TEST_SRC := $(filter %_test.c,$(SRCFILES)) # THEN: Convert test .c files to executable names (remove .c extension) TESTFILE := $(patsubst %.c,%,$(TEST_SRC)) # Default target: build the test executable all: $(TESTFILE) # Rule to build the test executable: depends on all object files $(TESTFILE): $(OBJFILES) $(CC) $(LDFLAGS) $(OBJFILES) -o $@ # Rule to build object files from .c files %.o: %.c $(CC) $(CFLAGS) $< -o $@
Key Fixes Explained
- Filtering test sources:
$(filter %_test.c,$(SRCFILES))grabs only the files that match the*_test.cpattern, soTEST_SRConly contains your test code files. - Generating test executable names:
$(patsubst %.c,%,$(TEST_SRC))takes those filtered.cfiles and removes the.cextension, giving you exactly theABC_testtarget you want. - Single
alltarget: We now have onealltarget that explicitly depends onTESTFILE, so runningmakewill prioritize building your test executable. - Cleaned up syntax: Removed the stray
---characters that were cluttering your variable definitions.
Testing It Out
Run make in your terminal—you should see your object files get built first, then the linker will combine them into your ABC_test executable (or whatever your _test.c file is named).
内容的提问来源于stack exchange,提问作者Krixen
相关产品推荐
相关产品推荐

