954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

compiling a list of C files with a Makefile

Hi,
I'm beginning with C and makefiles.

I'm trying to compile a list of C files with GNU Make.

My code should compile all the C files in the folder into .o files along with few flags and then use these .o files to compile an executable file 'main'.

and my code is this

CC=gcc
FLAGS=-l./-O3 -Wall -c
CFILES:=$(shell ls | grep .c)
OBJS:=$(CFILES:%.c=%.o)


all:$(OBJS)
	$(CC) $(OBJS) -o main

$(OBJS):$(CFILES)
	$(CC) $(FLAGS) $(CFILES)


Don't laugh please. This is not going to work as make is not going to compile each C file separately to build the final file main.

So please help.

Thanks in advance.

JDevelop
Newbie Poster
15 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

To compile individual files you have to either write an individual rule for each object, or use a generic rule as

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

(refer toautomatic variables chapter in info make for the meaning of @ and <). Put this rule in place of lines 10-11.
Also be advised that your makefile does not know that main is really a target, so it would rebuild main each time, even if nothing changed. Replace all at line 7 with main.
Another recommendation is to explicitly list the source files at line 3. If you really really want make to figure that list out, use $(wildcard *.c).
Finally, you need to spell out the objfiles dependencies on .h headers (otherwise the project wouldn't rebuild on a header modification). Add a generic rule:

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

a definition of generated .d fragments:

DEPS := $(CFILES:%.c=%.d)

and include them all:

-include $(DEPS)

After that you are pretty much set. There is still a room to perfect it.

nezachem
Posting Shark
903 posts since Dec 2009
Reputation Points: 719
Solved Threads: 194
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: