简体   繁体   中英

How to make `make` make an a executable for each C file in a folder?

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

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.)

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

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

all: $(EXEC)

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

SRCS = $(wildcard *.scm)

all: $(SRCS:.scm=)

%: %.scm
    chicken-csc -o $@ $<

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM