Xufeng
Xufeng

Reputation: 6762

Compile all source files into executables

I know that makefile is used for a project where files are related. But I want to use it in a different way.

Since I always write lots of test files, I need to type a bunch of flags every time I compile them, that's so troublesome. I just want to write a makefile that compiles all source files into executables with their corresponding names - like a.c to a and b.c to b, etc. so that I can get executables by simply typing make instead of the whole gcc ...

Is there any simple way to do it?

Upvotes: 2

Views: 64

Answers (3)

harmic
harmic

Reputation: 30597

Make has a built in implicit rule like this:

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

$(CFLAGS) would contain all your options.

Then, doing

make foo

Would try to produce foo from foo.c (if it existed).

To be able to compile all of them in one go, add another rule:

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

This new rule, called 'all', has the list of your executables as its prerequisite. The wildcard function lists all .c files in the directory, and the patsubst removes the .c from each of them, leaving a list of the executables that would be produced from each .c file.

So doing

make all

causes it to try to compile each .c file into the corresponding executable.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225272

make has built in implicit rules to do that. Just type make a or make b or make a b or whatever you want. Add and export an environment variable called CFLAGS if you want to add any special options.

Upvotes: 0

Moonhead
Moonhead

Reputation: 1568

Alright understood. I'm not too sure if you'll understand the syntax. I'll try to explain as much as I can.

you'll make a file called Makefile no extensions.

DIR=$(HOME)/../"Your directory"

all: "Whatever driver you may have"

purify: purify g++ -o "Your file" -Wall -pedantic -g "objective file .o extension"

# Makes clean file
clean:
        rm -f *.o  "Drivers"

new:
    make clean
    make

Upvotes: 0

Related Questions