An ideal GNU Makefile for C and C++ newbies

It's been a year or so I wanted to start using GNU Makefile in place of an IDE and this week I did a bit of a research and found the ideal Makefile that both newbies and mediocre programmers will find it handy.

The code below is taken from my C Makefile; please change the settings according your needs:

CC = gcc
# We include the current directory
INC = I.
CFLAGS = -Wall -pedantic -std=c99 -O2

# Enable this if you use threads in your program
# LDFLAGS = -pthread

TARGET = demo
OBJECTS = demo.o demo_main.o

all : $(TARGET)

# The PThread version
$(CC) -o $(TARGET) $(OBJECTS)  demo.o : demo.c demo.h

# The PThread version
# $(CC) $(CFLAGS) $(LDFLAGS) $(OBJECTS) -c demo.c
$(CC) $(CFLAGS) $(OBJECTS) -c demo.c

demo_main.o : demo_main.c

# The PThread version
# $(CC) $(CFLAGS) $(LDFLAGS) $(OBJECTS) -c demo_main.c
$(CC) $(CFLAGS) $(OBJECTS) -c demo_main.c

full : clean all

.PHONY : clean all

clean :
    rm -f $(TARGET) $(OBJECTS)


A small clarification: I'm using GNU / Linux Debian testing 64-bit, therefore the following code should work out of the box with GNU make.

So basically what am I doing here? In simple words, I'm first cleaning my already built binary files, both executable and object files, and then recompile my project; as simple as that.

So, every time I'm running make command, it would first clean the project and then rebuild it. Its behavior is so due to the use of special variable .DEFAULT_GOAL.

For more information about its behavior, please visit GNU make: Special Variables.

I hope you find it useful as much as I did.

Happy coding everyone.