Kalu
Kalu

Reputation: 290

How to convert a source c files to corresponding .o files using suffix rule in makefile?

Suppose we have a.c b.c c.c .So the make file will like this

app:  a.o b.o c.o 
    gcc  -o app.o a.o b.o c.o

a.o:   a.c
    gcc  -c  a.c

b.o:    b.c
    gcc  -c  b.c

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

In the future more C files may be added. So do I need to make target of .o extensions for each .c file. I got to know about suffix rules which uses the .source-extension.target-extension. But I could understand how to use this suffix rule in the make file. Please provide me the command to be included in make file and please describe the syntax.I am newbie to makefile.

Upvotes: 0

Views: 2697

Answers (2)

rashok
rashok

Reputation: 13434

Below is the sample makefile for compiling c code.

TARGET = a.out
SRCS = a.c b.c c.c
OBJS = $(SRCS:.c=.o)

CFLAGS = -g -ggdb -O2 -Wall -Werror

CC = gcc
RM = rm

.PHONY: all clean

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

$(TARGET) : $(OBJS)
    $(CC) $^ -o $@

clean:
    $(RM) *.o
    $(RM) $(TARGET)

Upvotes: 0

Santosh A
Santosh A

Reputation: 5351

You can use the below makefile.

app:  a.o b.o c.o 
    gcc -o $@ $^

a.o : a.h
b.o : b.h
c.o : c.h

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

Where $@ is the target(app), $^ is the list of dependencies and $< is the corresponding c file to compile to object file

Upvotes: 1

Related Questions