Ankur Agarwal
Ankur Agarwal

Reputation: 24758

Writing makefile to compile several binaries

I am trying to write a Makefile to compile 87 files with the following names: file1.c, file2.c file3.c .... file87.c

I am trying to compile them into separate binaries with names: file1, file2, file3 .... file87

In the Makefile I need to define following variables for each and every one of them. This is what I had originally.

FILE1 = file1
$(FILE1)_SRC := \
        mydir/file1.c \
        mydir/another.c

$(FILE1)_CFLAGS := `pkg-config --cflags glib-2.0`
$(FILE1)_LDFLAGS := -L. `pkg-config --libs glib-2.0`

FILE2 = file2
$(FILE2)_SRC := \
        mydir/file2.c \
        mydir/another.c

$(FILE2)_CFLAGS := `pkg-config --cflags glib-2.0`
$(FILE2)_LDFLAGS := -L. `pkg-config --libs glib-2.0`

Also at the end of the Makefile I need to store the names of the binaries

binaries = $(FILE1) $(FILE2) ...... $(FILE87)

I explored loops and define directive in make but I cannot understand how can I do this neatly in a non-cumbersome manner. Please note the CFLAGS and LDFLAGS are same for all of them.

Any inputs or alternative approaches to writing the Makefile are very welcome.

I wrote this based on seldon's answer below, but this gives an error:

SRCS = $(wildcard mydir/*.c)
TGTS = $(SRCS:%.c=%)

CFLAGS  = $$(pkg-config --cflags glib-2.0)
LDFLAGS = -L.
LDLIBS  = $$(pkg-config --libs glib-2.0)

all: $(TGTS)
    @echo $(SRCS)
    @echo $(TGTS)

$(TGTS) : % : %.o another.o

#clean:
 #   rm -f $(TGTS) *.o

#.PHONY: all clean

$ make
cc $(pkg-config --cflags glib-2.0)   -c -o mydir/another.o mydir/another.c
make: *** No rule to make target `another.o', needed by `mydir/another'.  Stop.

Source:

another.c

# include <stdio.h>
# include <stdlib.h>

void print_string(const char * file_name, int lineno, const char * func_name) {

    printf("%s %d %s\n", file_name, lineno, func_name);

}

file01.c

int main() {

    print_string(__FILE__, __LINE__, __func__);
}

Any help appreciated.

Upvotes: 1

Views: 454

Answers (1)

seldon
seldon

Reputation: 510

If the variables are the same for all programs, you could use a static pattern rule like this:

SRCS = $(wildcard file*.c)
TGTS = $(SRCS:%.c=%)

CFLAGS  = $$(pkg-config --cflags glib-2.0)
LDFLAGS = -L.
LDLIBS  = $$(pkg-config --libs glib-2.0)

all: $(TGTS)

$(TGTS) : % : %.o another.o

clean:
    rm -f $(TGTS) *.o

.PHONY: all clean

Upvotes: 3

Related Questions