makefile Tutorial

Makefile是一种用于构建和编译项目的工具,通常用于C/C++项目,但也可以用于其他编程语言。Makefile使用一种特定的语法来定义项目中的规则和依赖关系。以下是Makefile的基本语法要点:

  1. 目标(Targets):目标是您要构建的文件或任务的名称。通常,第一个目标是默认目标,可以通过运行make命令来构建。

    1
    2
    target: dependencies
    command
    • target是目标的名称。
    • dependencies是目标的依赖项,可以是其他目标或文件。
    • command是构建目标的命令。
  2. 规则(Rules):规则定义了如何构建目标以及它的依赖项。规则通常出现在Makefile中。

    1
    2
    target: dependencies
    command

    例如:

    1
    2
    build: main.go 
    go build -o bin/main main.go
  3. 变量(Variables):您可以在Makefile中定义变量,以便更轻松地重用值。

    1
    2
    3
    4
    BINARY = "BINARYFileName"

    build: main.go
    go build -o bin/${BINARY} main.go
  4. 条件语句(Conditionals):Makefile支持条件语句,您可以根据条件执行不同的命令。

    1
    2
    3
    4
    5
    6
    BINARY = "BINARYFileName"

    clean:
    @if [ -f ${BINARY} ]; then
    rm ${BINARY}
    fi
  5. 伪目标(Phony Targets):伪目标不代表实际的文件,而是表示特定任务。它们通常用于指定清理(clean)或其他非文件生成任务。

    1
    2
    3
    .PHONY: clean
    clean:
    rm -f my_program

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 声明变量
BINARY="BIANRYFileName"
# 使用make指令时,执行all中的所用target
all: goTool build

goTool:
go fmt ./
go vet ./

build:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ./bin/${BIANRYFileName}
#go build -o bin/main main.go

run:
go run main.go

clean:
@if [ -f ${BINARY} ]; then
rm ${BINARY}
fi

compile:
echo "Compiling for every OS and platform"
#GOOS=freebsd GOARCH=386 go build -o bin/main-freebsd-386 main.go
GOOS=linux GOARCH=386 go build -o bin/main-linux-386 main.go
#GOOS=windows GOARCH=386 go build -o bin/main-windows-386 main.go



makefile Tutorial
http://example.com/2023/10/25/Tutorial/
作者
Forrest
发布于
2023年10月25日
许可协议