关于Makefile的技术疑问:中间文件与独立源码编译
Question 1: Removing .o File Generation Commands
Great question about intermediate .o files! Your intuition is correct—you absolutely can skip explicit .o targets and use a more concise command to build your executable directly.
For example, if you have source files a.c, b.c, c.c and want to build an executable myprog, you can write this in your Makefile:
myprog: a.c b.c c.c gcc $^ -o $@
When you run make, this will compile all the source files together in one step and output only the myprog executable—no .o files will be left behind (gcc doesn't keep intermediate object files unless you use the -c flag).
That said, there's a tradeoff: if you modify just one source file later, this approach will recompile all sources instead of only the changed one. If your project is small, this isn't a big deal, but for larger projects, keeping .o files (using explicit targets or Make's implicit rules) saves time on incremental builds.
Question 2: Compiling Independent Source Files Separately
If your three source files are unrelated and each should become its own executable (say prog1 from prog1.c, prog2 from prog2.c, prog3 from prog3.c), here's the correct way to set this up:
Option 1: Explicit Targets
# Default target: build all three executables all: prog1 prog2 prog3 # Build each executable from its source file prog1: prog1.c gcc $< -o $@ prog2: prog2.c gcc $< -o $@ prog3: prog3.c gcc $< -o $@ # Clean up the executables clean: rm -f prog1 prog2 prog3
Option 2: Pattern Rule (More Concise)
If you have many such files, a pattern rule avoids repetition:
all: prog1 prog2 prog3 # Match any target % where there's a corresponding %.c file %: %.c gcc $< -o $@ clean: rm -f prog1 prog2 prog3
If your previous attempt wasn't generating separate executables, it's likely you tried to put all sources under a single target (which would only build one executable) or didn't define individual targets for each program. With the above setups, running make will build all three executables, and each is compiled independently from its source file.
内容的提问来源于stack exchange,提问作者Thomas D.

