Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a clean Makefile?

Tags:

makefile

The Makefiles that I have dealt with, for the most part, are complex and hide a lot of relationships. I have never written one myself, and was wondering if anybody had some tips on writing a Makefile that is easy to read and reusable?

like image 469
cssndrx Avatar asked Jul 06 '11 17:07

cssndrx


2 Answers

I usually use something like this, in this example the source files are main.c file2.c file3.c file4.c, to add more you simply add to the OBJECTS var.

They all depend on Makefile, so for a full recompile a simple touch Makefile would suffice.

PROGNAME = hi2u
LIBS = -ljpeg -ldirectfb -pthread 
INCLUDES = -I/usr/local/include/directfb 
LDFLAGS = -Llibs/
OBJECTS = main.o file2.o \
            file3.o file4.o

CFLAGS = -W -Wall -O2 -ggdb 

all: $(PROGNAME)

$(PROGNAME): $(OBJECTS)
    gcc -o $(PROGNAME) $(OBJECTS) $(LIBS) $(INCLUDES) $(LDFLAGS)

$(OBJECTS): Makefile

.c.o: 
    gcc -c $(CFLAGS) $(INCLUDES) -o $@ $< 

clean:
    rm *.o $(PROGNAME)
like image 89
Vinicius Kamakura Avatar answered Sep 22 '22 19:09

Vinicius Kamakura


In all honesty, the complexity of a makefile relies on the complexity of the program. If you have a lot of folders and files and different compiling processes, you're makefile is probably going to be a little long and complicated. If you have a helloworld program, there's no reason for it to be longer than a few lines.

Here's some tips on makefiles : http://mrbook.org/tutorials/make/

Here's a very reusable makefile that's not too complicated:

CC=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=main.cpp hello.cpp factorial.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=hello

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS) 
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@
like image 30
rlb.usa Avatar answered Sep 23 '22 19:09

rlb.usa