tags:

views:

130

answers:

2

can anybody please explain the working of '$< and $@' in Makefile?

+11  A: 

$< evaluates to the first "prerequisite" in the make rule, and $@ evaluates to the "target" in the make rule.

Here's an example:

file.o : file.c
             $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@

In this case, $< will be replaced with "file.c" and $@ will be "file.o"

These are more useful in generic rules like this:

%.o : %.c
             $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@

See this manual for more info:

http://www.gnu.org/software/make/manual/make.html#Automatic-Variables

Andy White
Note that while the above two examples will work with GNU Make, they are not portable. POSIX doesn't define % rules, and it defines $< only for suffix rules (i.e., as Laurence Gonslaves showed in his answer).The standard definitions of these variables are better read here :http://www.opengroup.org/onlinepubs/009695399/utilities/make.html
adl
On the other hand, writing Makefiles becomes so much easier if you restrict yourself to GNU make. (which is portable to more or less any all existing platforms)
JesperE
(...waiting for someone to tell me which platforms GNU make is not available on...)
JesperE
They are also important when using VPATH, since they will expand to the directory in which the source file was found.
JesperE
+3  A: 

$@ is the target of the current rule. $< is the name of the first prerequisite ("source") of the current rule.

So for example:

.c.o:
        $(CC) -c $(CFLAGS) -o $@ $<

This will expand to a command something like:

gcc -c -Wall -o foo.o foo.c

See also the GNU Make documentation.

Laurence Gonsalves