I have created few files and Makefile in the same place.
I have read in below link about the special variables $@ and $< and used as so.
but when the say make i keep getting the error

gcc -o calc *.o
/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status
make: *** [calc] Error 1

i have just started learning makefiles and understood basic makefile but using advance concepts is difficult.

%.o: %.c
        gcc -c -o $@ $<
calc : *.o
        gcc -o calc *.o
clean :
        rm *.o

Recommended Answers

All 4 Replies

It is a very bad habit to use an asterisk in the dependency. Consider the situation:
foo.c bar.c are the sources. For some reason foo has been compiled into foo.o, but bar.c was not. The directory contains foo.c, bar.c, and foo.o. The dependency *.o at line 4 in your makefile evaluates to just foo.o so bar.c is never compiled.

The solution is to spell your object files explicitly:

objects = foo.o bar.o baz.o
calc: $(objects)
    gcc -o calc $(objects)

There are advanced techniques, but for now do spell your objects out.

Thanks Nezachem for your point.
I actually want to automatically add .c and .o files whenever i create a new .c files.

can anybody explain what the variables $@ and $< mean.

I actually want to automatically add .c and .o files whenever i create a new .c files.

Umm... there is a way, read on the wildcard function and stem substitution, as in

SOURCES := $(wildcard *.c)
OBJECTS := $(SOURCES: %.c=%.o)
calc: $(OBJECTS)
    gcc -o calc $(OBJECTS)
%.o: %.c
    gcc -c $< -o $@

In my opinion, wildcard is a misfeature (if you wish I may elaborate). In any case do not try to use it until you comfortably understand the basic make functionality.
Make's way of thinking is sort of convoluted. Take small steps to get used to it.

can anybody explain what the variables $@ and $< mean.

$@ in a recipe means a target name. For example,

foo.o: foo.c
    gcc -o foo.o foo.c

is the same as

foo.o: foo.c
    gcc -o $@ foo.c

Similarly, $< means a prerequisite name:

foo.o: foo.c
    gcc -o $@ $<

Not much of a value for the explicit rules, but very useful for the stem rules, such as

%.o: %.c
    gcc -o $@ $<

Thank you verymuch Nezachem.

understood the varibles..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.