文章

「英语」C++ Makefile

「英语」C++ Makefile

Makefiles are special format files that together with the make utility will help you to automagically build and manage your projects. (From davetang.org)

Compile Steps:

  • Preprocessing the source code.
  • Compiling the source code.
  • Assembling the compiled file.
  • Linking the object code file to create an executable file.

C++ build process

▲ (The photo above is from: niu.edu)

Create Object File

This is accomplished by adding the -c directive to the g++/gcc compiler

  • g++ -c testFile.cpp
    • -> testFile.o
  • The -c option lets us compile and get around certain restrictions
    • Such as not requiring a main() function
  • The .o file is compiled code that doesn’t have enough information to run by itself. and therefore is not executable.

Makefile

A Makefile consists several entries:

  • Each entry has:
    • A target (usually a file)
    • Dependencies (files which the target depends on)
    • Commands (based on the target and dependencies)
1
2
<target> : <dependancy list>
	<command>

For example:

1
2
testFile.o: testFile.cpp testFile.h foo.h
	g++ -Wall -c testFile.cpp

Interpretation: If we want to create testFile.o, then testFile.cpp, testFile.h, foo.h must exist. If they do, run the command g++ -Wall -c testFile.cpp.

A First Sample Makefile

Imagine a project has 3 files

1
circle.cpp circle.h main.cpp

circle.h is the header file. circle.cpp is the implementation of circle.h header file. main.cpp is the entry file.

To create a Makefile

1
2
3
4
5
6
7
8
9
10
11
exe: circle.o main.o
	g++ -g -Wall circle.o main.o -o exe
	
circle.o: circle.h circle.hpp
	g++ -g -Wall -c circle.cpp
	
main.o: circle.h main.cpp
	g++ -g -Wall -c main.cpp
	
clean:
	rm *.o exe *~ -v

Interpretation: If we want to create exe, then circle.o, main.o must exist. They don’t, generate a circle.o and main.o through the following command. Finally, create an exe file.

It is brute force, but it works.

Makefile Macros

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
OBJS = circle.o main.o
CC = g++
DEBUG = -g
CFLAGS = -Wall -c $(DEBUG)
LFLAGS = -Wall $(DEBUG)
EXE = exe

$(EXE): $(OBJS)
	$(CC) $(LFLAGS) $(OBJS) -o $(EXE)
	
circle.o: circle.h
	$(CC) $(CFLAGS) circle.cpp
	
main.o: circle.h
	$(CC) $(CFLAGS) main.cpp
	
clean:
	rm *.o $(EXE) *~ -v

References

Makefile - Dave’s wiki

本文由作者按照 CC BY 4.0 进行授权