Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make: wildcard to use all object files

Tags:

makefile

I have a Makefile that looks like this:

CC=cc
CFLAGS=-g -std=c99 -Wfatal-errors
OBJS=$(wildcard *.o)

all: main.o cmdargs.o io.o
    $(CC) -o app $(OBJS)

main.o: main.c
    $(CC) -c main.c $(CFLAGS)
cmdargs.o: cmdargs.c
    $(CC) -c cmdargs.c $(CFLAGS)
io.o: io.c
    $(CC) -c io.c $(CFLAGS)

clean:
    @rm -rf app $(OBJS)

Whenever I run make all after a clean, there's an error saying

cc -o

undefined reference to `main'

But when I run it a second time everything works as expected. What is wrong with the script, and how can we fix it?

like image 229
Anonymous Entity Avatar asked Oct 20 '25 21:10

Anonymous Entity


1 Answers

The previous respondents gave good answers but not complete. So let me post one too.

First of all, it is a bad idea to use wildcard in makefiles. It is much better to not be lazy and list your files explicitly.

If you must be lazy, the way to use wildcard is, as shawncorey writes, to use it for sources.

Also, do not have a recipe for phony targets such as all. In your example, the recipe for all will always run, which is inefficient.

CC := gcc

SRCS := $(wildcard *.c)
OBJS := $(SRCS:c=o)

.PHONY: all clean

all: app 

app: $(OBJS) Makefile
    $(CC) -o $@ $(OBJS)

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

clean:
    @rm -rf app $(OBJS)
like image 166
Mark Galeck Avatar answered Oct 24 '25 05:10

Mark Galeck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!