How to write a clean makefile?

The makefiles I have been working with are for the most part complex and hide many relationships. I never wrote it myself and wondered if anyone has any tips on writing a Makefile that is easy to read and reuse?

+6
source share
4 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 just add var to OBJECTS .

They all depend on the Makefile , so a simple touch Makefile enough to completely recompile.

 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 .co: gcc -c $(CFLAGS) $(INCLUDES) -o $@ $< clean: rm *.o $(PROGNAME) 
+3
source

The tutorial I found helpful in understanding the Makefile is http://www.jfranken.de/homepages/johannes/vortraege/make_inhalt.en.html

Another tip is to make extensive use of regular expressions for source files and dependencies.

+2
source

For me, the reading that made me think about these issues is the classic "Recursive view is considered harmful ."

When I get the opportunity to create make files from scratch, I try to use implicit rules as much as possible, as well as define rules in a separate file that I can include in a β€œreal” make file.

Problems using make can be divided into two main groups:

  • problems inherent in make itself, its rich semantics and syntax, and somewhat archaic appearance

  • problems that do not make a β€œmistake”, but come from the moment when make is used to invoke another make process. Suddenly, we have another task - communication between two or more processes. It is very easy to get lost in environmental variables or other ways of transmitting information. The differences in the platform that make are meant to be hidden can become visible.

+1
source

Honestly, the complexity of the makefile depends on the complexity of the program. If you have many folders and files and different compilation processes, you makefile is likely to be a little long and complicated. If you have a helloworld program, there is no reason for it to be longer than a few lines.

Here are some tips for makefiles: http://mrbook.org/tutorials/make/

Here is a very reusable make file that is 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 $@ 
+1
source

Source: https://habr.com/ru/post/892161/


All Articles