8

My question is deceptively simple, but I have lost several hours of study trying to get the solution. I'm trying to create a Makefile that builds an executable for each .c file in a directory.

I have tried the following:

CC = gcc
SRCS = $(wildcard *.c)
OBJS = $(patsubst %.c,%.o,$(SRCS))

all: $(OBJS)
$(CC) $< -o $@

%.o: %.c
    $(CC) $(CPFLAGS)  -c  $<

but this way it is creating only .o files, and not any executables. I need a rule that makes an executable for each of these .o files. Something like the following:

gcc src.o -o src
Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
eduardomoroni
  • 4,140
  • 1
  • 21
  • 18
  • FWIW, HTH http://stackoverflow.com/questions/5950395/makefile-to-compile-multiple-c-programs/13696012#13696012 – Robert Dec 04 '12 at 12:43

4 Answers4

7

rob's answer doesn't seem to work on my machine. Perhaps, as the complete Makefile:

SRCS = $(wildcard *.c)

all: $(SRCS:.c=)

.c:
     gcc $(CPFLAGS) $< -o $@

(The last two lines, are on my machine, unnecessary, as the default rules are adequate.)

Community
  • 1
  • 1
Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
  • 1
    That's exactly what I wanted. Very Thank. was not able to properly use ':.' – eduardomoroni Apr 04 '12 at 11:04
  • @eduardomoroni: You should note that the name of your macro `CPFLAGS` is non-standard. It should typically be `CFLAGS` or `CPPFLAGS` or both. See [CFLAGS vs CPPFLAGS](//stackoverflow.com/q/2754966). – Joseph Quinsey Mar 06 '18 at 17:47
  • 1
    Nice answer. What about adding a `clean` target ? – Arkaik Jun 25 '18 at 09:07
  • For at least GNU `make` the `.c` rule is entirely unnecessary (and isn't worth its own declaration) -- GNU `make` knows how to build from C files without explicit rules. Otherwise all good :) – Armen Michaeli Mar 27 '21 at 19:55
2

Your all is telling it just to build the object files. Add something like

EXEC = $(patsubst %.c,%,$(SRCS))

all: $(EXEC)

rob
  • 2,053
  • 15
  • 13
1

Try the following:

% : %.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<
all: $(basename $(wildcard *.c))

and you don't even need the first two lines, as make knows how to compile and link .c files into executables. Still, it is often necessary to change make's built-in recipes.

Idelic
  • 14,976
  • 5
  • 35
  • 40
1

This is the Makefile I use to compile a bunch of scheme files.

SRCS = $(wildcard *.scm)

all: $(SRCS:.scm=)

%: %.scm
    chicken-csc -o $@ $<
Joaquin
  • 11
  • 1