Go 条件编译

GOPATH 环境变量, 我这里设置为  "d:\golang\"    目录golang

代码目录结构bash

 

d:\golang\src\tagerTest\main.go函数

// tagerTest project main.go
package main

import (
	"fmt"
	"tagerTest/test"
)

func main() {
	test.Myprint()
	fmt.Println("Hello World!")
}

d:\golang\src\tagerTest\test\p1.goui

// +build !xx

package test

import (
	"fmt"
)

func Myprint() {
	fmt.Println("myprint in p1")
}

d:\golang\src\tagerTest\test\p2.gospa

// +build xx

package test

import (
	"fmt"
)

func Myprint() {
	fmt.Println("myprint in p2")
}

从上面咱们看到 p1.go 和 p2.go 中都存在 Myprint() 这个函数code

咱们如今来编译看看输出结果!编译

D:\golang\src\tagerTest>go build

D:\golang\src\tagerTest>.\tagerTest.exe
myprint in p1
Hello World!

没有编译问题,输出结果调用的是  p1.go 里面的 Myprint() 函数!class

那么怎么调用 p1.go 里面的 Myprint() 函数了 ?test

D:\golang\src\tagerTest>go build -tags=xx

D:\golang\src\tagerTest>.\tagerTest.exe
myprint in p2
Hello World!

在 编译的时候加上了 -tags=xx,编译后发现调用的就是 p2.go 里面的 Myprint() 函数了import

 

条件编译

咱们发现,条件编译的关键在于-tags=xx,也就是-tags这个标志,这就是Go语言为咱们提供的条件编译的方式之一。

好了,回过头来看咱们刚开始时 test\p1.go、 test\p2.go两个Go文件的顶部,都有一行注释:

// +build !xx

// +build xx

// +build !xx表示,tags不是xx的时候编译这个Go文件。这两行是Go语言条件编译的关键。+build能够理解为条件编译tags的声明关键字,后面跟着tags的条件。

// +build xx表示,tags是xx的时候编译这个Go文件。

也就是说,这两种条件是互斥的,只有当tags=xx的时候,才会使用p2.go 里面的 Myprint,其余状况使用p1.go 里面的 Myprint

相关文章
相关标签/搜索