Makefile代码含义咨询:.c.o目标规则解析
Hey there! Let's break down these Makefile rules clearly—they're a classic (though slightly old-school) way to compile C source files into object files, so I'll walk through each part step by step.
.c.o mean? That's a suffix rule in Makefile syntax. Think of it as a generic rule that says: "For any .o object file you need to build, if there's a corresponding .c source file with the same base name, use this rule to create the .o file from the .c file."
It's a shorthand for "convert .c files to .o files"—back in the day, this was the standard way to define this kind of conversion, though modern Makefile best practices prefer pattern rules like %.o: %.c (we'll touch on that later).
Let's unpack the two rules you shared
1. .c.o : gcc –c $*.c
Let's break down the variables and commands here:
$*is a Make automatic variable that represents the "stem" of the target file—meaning the target name without its suffix. For example, if you're buildingfoo.o,$*becomesfoo.- So when this rule runs for
foo.o, it expands togcc -c foo.c, which compilesfoo.cintofoo.o(GCC's-cflag tells it to stop at compiling, not link into an executable).
The catch here: $* only works if your .c source file has exactly the same base name as the .o target. If you ever have a scenario where, say, bar.o comes from bar_main.c, this variable won't help you—it's tied strictly to matching base names.
2. .c.o : gcc –c $<
This uses a different automatic variable, $<, which is far more flexible:
$<represents the first dependency file of the target. For the.c.osuffix rule, the implicit dependency is the matching.cfile (sofoo.cforfoo.o).- Just like the first rule, this expands to
gcc -c foo.cforfoo.o—but here's the advantage:- If you ever modify the rule to include additional dependencies (like header files),
$<will still correctly point to the.cfile (the first dependency) instead of breaking. - It plays nicer with more complex rule setups, whereas
$*is limited to matching base names.
- If you ever modify the rule to include additional dependencies (like header files),
While these suffix rules work perfectly fine, most modern Makefile writers prefer pattern rules because they're more explicit and readable. The equivalent pattern rule for .c.o would be:
%.o: %.c gcc -c $< -o $@
Here, $@ is another automatic variable that represents the target file name (e.g., foo.o). This does exactly the same job as the suffix rules, but it's clearer what's happening at a glance.
Also, keep in mind: Make actually has built-in implicit rules for compiling .c to .o by default. People often write custom rules like these to add compiler flags (e.g., -Wall for warnings, -O2 for optimizations) that aren't included in the default setup.
内容的提问来源于stack exchange,提问作者Lina Hammami

