how to fix error 'no rule to make target %.o, needed by all. stop'

Viewed 879

When I type make and hit enter, it says:

no rule to make target %.o, needed by all. stop'. 

This is my makefile:

CC=g++
LDFLAGS=""

all: %.o %.h
    $(CC) $< $(LDFLAGS) -o bin

%.o: %.cpp %.h
    $(CC) -c $< 

These are the contents of my directory:

$ ls
main.cpp makefile

I'm new to GNU make and just learned to use automatic variables. Can someone help me out?

2 Answers

% is for substituting patterns, which is what you want when defining a rule for a single module (like you did), but not what you want as the dependency list of 'all'. A % will expand to a single value.
Instead, you want an actual wildcard (like in the shell expansion) to match all *.o files. So, change your target definition to

all: *.o *.h

Not related to your question, but this is not right:

LDFLAGS=""

make doesn't parse quotes, so you've set the variable LDFLAGS to the literal string "" (two double-quotes). When you use that in your recipe:

$(CC) $< $(LDFLAGS) -o bin

it will be as if you'd typed:

g++ ... "" -o bin

which is a syntax error (you're passing an empty argument to g++. If you want an empty variable you just write:

LDFLAGS =

Now, your problem. This is not a pattern rule:

all: %.o %.h

A pattern rule must have a pattern in the target (left-hand side of the colon). Since this is an explicit rule, the prerequisites (the right-hand side of the colon) are the literal strings %.o and %.h. Make doesn't know how to build a file named %.o so it fails.

It's not really clear what you expect this rule to do, so I can't say more than that.

Related