David
David

Reputation: 1265

How to make this Makefile more concise?

I know there are ways to remove duplicates $(CC) $(CFLAGS) $@ $^ in Makefile. Can you tell me how to make the Makefile below more concise?

CC=gcc
CFLAGS=-pthread -g -o

all: p1 p2

p1: p1.c
    $(CC) $(CFLAGS) $@ $^

p2: p2.c
    $(CC) $(CFLAGS) $@ $^

Upvotes: 0

Views: 411

Answers (2)

Didier Trosset
Didier Trosset

Reputation: 37427

To make your Makefile more concise, you can write it as follows.

CC=gcc
CFLAGS=-pthread -g -o

all: p1 p2

%: %.c
    $(CC) $(CFLAGS) $@ $^

Then you can add as many p's as you want on the all: line. As long as you provide pN.c, make will compile them into the corresponding pN.

Upvotes: 2

snim2
snim2

Reputation: 4079

Yes, you can combine commands "by prerequisite". For example:

CC=gcc
CFLAGS=-O3
INCLS=-I$(BASEDIR)/include
LIBS=$(BASEDIR)/lib/thread.a
OBJS = dotprod_mutex.o dotprod_serial.o
EXEC = dotprod

$(EXEC): $(OBJS)
         $(CC) -o $(EXEC) $(OBJS) $(LIBS)
$(OBJS): dotprod.h
         $(CC) $(CFLAGS) $(INCLS) -c $*.c

or somesuch -- you'll need to go through the details and make sure those libraries and so on actually make sense.

Note that the phrase $(OBJS): dotprod.h means that $(OBJS): depends on the presence of dotprod.h.

You will want to read the manual to get all the gory details, in particular:

As for tools to automate this stuff, you want automake and autoconf: http://sourceware.org/autobook/

Upvotes: 1

Related Questions