程序的一般過程:編輯、編譯、鏈接、運行。由於golang的一個項目源碼都是開源的,我們很少去關心編譯、鏈接的問題。如果在一個項目中使用了非開源的第三方庫,此時怎么打包出來一個可執行的exe程序?
golang使用靜態文件編譯
使用go tool compile
golang使用靜態文件鏈接
使用go tool link
//staticpkg/print.go
package staticpkg
import "fmt"
func Hello() {
fmt.Println("hello")
}
//運行 go install 會生成對應的.a文件
//修改print.go文件,去掉函數實現,
//main/main.go
package main
import (
"staticpkg"
)
func main() {
staticpkg.Hello()
}
//使用tool的compile命令編譯當前項目
go tool compile -I $GOPATH/windows_amd64 main.go
//會生成一個main.o文件
//使用tool的link命令生成可執行文件
go tool link -o main.exe -L $GOPATH/windows_amd64 main.go
//會生成一個main.exe程序,直接運行會輸出hello
//如果直接go run main.go此時沒有任何輸出
使用靜態文件(.a文件)進行編譯和鏈接時,只需要有對應的.a文件即可。但是.a文件是無法查看到對應包中的一些定義的,如果要使用.a文件進行開發,還需要一份對應的聲明文件。
https://github.com/golangaccount/exporthead是一個簡單的導出go package聲明的項目,里面移除了函數的實現細節和type或interface中的非導出item