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

相關文章
相關標籤/搜索