multivac61
multivac61

Reputation: 35

How can I use GNU make to compile multiple nonrelated source files into multiple nonrelated object files?

I have been learning about gnu make and Makefiles. Makefiles have make my life easier when I'm working with many dependent object, header and source files. I've heard that make can be used to do all kinds of automation-magic so I'm curious know whether I can use it to compile unrelated files with unrelated main functions into unrelated object files and that all in the same dir.

Here's some code that should do what I want:

CC=gcc
CFLAGS=-g -Wall -std=gnu99 -DNDEBUG
all:
    $(CC) $(CFLAGS) file1.c -o file1
    $(CC) $(CFLAGS) file2.c -o file2
    $(CC) $(CFLAGS) file3.c -o file3
    $(CC) $(CFLAGS) file4.c -o file4
    etc...

I know how to make a list of *.c files and then the corresponding object files is done like so:

TARGET=$(wildcat *.c)
OBJECTS=$(patsubst %.c,%,$(SOURCES))

But that only gives me a list of files respectively. How can I work with individual files within that list so that I can compile one file at a time?

Upvotes: 0

Views: 145

Answers (3)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16039

In fact, the rule for making *.o files from the corresponding *.c files is part of the built-in rule set for make: call $(CC) -c on the c file. That is, for that task you don't even need a Makefile, much less list the single sources in it. Just say "make whatevername.o".

Upvotes: 0

multivac61
multivac61

Reputation: 35

All figured out, thank you all for your inputs. Here's one simple solution which does exactly what I was looking for:

SOURCES=$(wildcard *.c)
OBJECTS=$(patsubst %.c,%,$(SOURCES))
all: $(OBJECTS)

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45674

Make is a so-called rule-based expert system. You give it the rules for determining dependencies and what to do for each step (There are already many generic pattterns you can override predefined), give it a target, and make determines how to get there and what all to (re-)execute.

Nobody stops you from giving make an explicit target, instead of letting it do the default one (normally the first in your makefile).

Override dependencies this way:

all: file1 file2 file3

Upvotes: 0

Related Questions