You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

  1. Incorrect test file filtering: Your TESTFILE variable uses patsubst %_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—so TESTFILE ends up containing a mix of your test target and every other source file name (without extensions), which makes the build rule confused.
  2. Duplicate all targets: You've defined all twice. Make will only use the last definition, so your first all: $(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.c pattern, so TEST_SRC only contains your test code files.
  • Generating test executable names: $(patsubst %.c,%,$(TEST_SRC)) takes those filtered .c files and removes the .c extension, giving you exactly the ABC_test target you want.
  • Single all target: We now have one all target that explicitly depends on TESTFILE, so running make will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:44:07