Makefile自定义函数cap输出异常问题咨询:执行make f为何打印@echo指令而非预期内容
Why This Happens
The issue comes down to how Make validates recipe lines and the structure of your cap function.
In your original Makefile, the cap function generates @echo $1 without a leading tab. When foreach expands, only the first line of the resulting recipe has a leading tab (inherited from the original f: rule's recipe line). The subsequent lines (@echo x2, @echo x3, etc.) lack this required tab.
Make requires every recipe line to start with a tab (or the custom character set in .RECIPEPREFIX). Lines without this tab aren't treated as valid command lines. Instead of executing @echo x2 as a command, Make ends up printing the literal @echo x2 text.
Fixes
Here are a few straightforward ways to resolve this:
Fix 1: Include a Tab in the cap Function
Modify the cap function to include a leading tab before @echo. This ensures every line generated by foreach is a valid recipe line:
define cap @echo $1 endef f: $(foreach x,$(shell command),$(call cap,$x))
(Important: The line inside define cap must start with a tab, not spaces.)
Fix 2: Use a Single Shell Command with Semicolons
If you don't mind running all echo commands in a single shell instance, simplify the recipe to a single line with @ to suppress command echoing:
f: @$(foreach x,$(shell command),echo $(x);)
This will print each xN on a new line without showing any underlying echo commands.
Fix 3: Add Tab and @ Directly in the foreach Call
Keep the cap function simple, and handle the tab and @ prefix within the foreach loop:
define cap echo $1 endef f: $(foreach x,$(shell command), @$(call cap,$x))
Again, ensure the line inside the foreach starts with a tab.
Expected Output
Any of these fixes will produce your desired result:
x1 x2 x3 x4 x5
内容的提问来源于stack exchange,提问作者NinjaGaiden

