Makefile Shell – Fixing Sed Regexp End of Line Ignoring in Makefile

makequotingshellspecial characters

I have a folder for various testing of C code, containing many files named *.c. My aim is to have a Makefile search for any filename ending in .c and add the root of that filename to the targets.

Makefile:

TARGETS = $(shell ls *.c | sed "s/\.c$//g")
all: $(TARGETS)

The issue is that the shell command works as expected in sh:

$ sh -c 'ls *.c | sed "s/\.c$//g"'
hello

…while it fails with make:

$ make
sed: 1: "s/\.c/g": unterminated substitute in regular expression
make: Nothing to be done for `all'.

I tried escaping the $ as \$, which instead yields:

`sed: 1: "s/\.c\/g": unterminated substitute pattern`

The same goes for replacing the double quotes (") with single quotes (').

Best Answer

With GNU Make:

objects := $(patsubst %.c,%.o,$(wildcard *.c))

all : $(objects)

See info make or pinfo make and search for the wildcard and patsubst functions for more details. Depending on your distro, you may need to install the make-doc package (or similar name) first to get the full make documentation.

Related Question