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.

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 to automatic 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.