「英语」C++ Makefile

最后更新于:2022-11-26

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)
<target> : <dependancy list>
    <command>

For example:

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

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

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

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

标签: Linux, 原创, C++

评论已关闭。 了解详情