Go按照條件編譯

來源:互聯網
上載者:User

標籤:

Go 支援按照條件編譯,具體來說它是通過 go/build包 裡定義的tags和命名規範來讓Go的包可以管理不同平台的代碼 。

我們這裡以下面這個開源項目為例,來看Go的按條件編譯, 這個開源項目是把Go的os包進行了擴充。

https://bitbucket.org/kardianos/osext/src 

 

osext 是獲得當前執行程式的執行目錄和檔案資訊。

執行情況如下:

 

查看編譯檔案

我們用go list來查看在當前平台下 os/exec包裡有哪些檔案將會被編譯

看當前項目下,有哪些檔案會被編譯,命令如下:

這裡的 {{.GoFiles}} 是text/template裡的模板代碼

 

go list 命令的資訊如下:
查看包名、路徑、依賴項等等資訊。
參數:
-json: 使用 json 格式輸出包的相關資訊,包括下面的依賴和導?。
-f{{.Deps}}: 查看依賴包,包括直接或間接依賴。
-f{{.Imports}}: 查看匯入的包。

 

D:\mycodes\golang\src\bitbucket.org\kardianos\osext>go list -f
flag needs an argument: -f
usage: list [-e] [-f format] [-json] [build flags] [packages]

List lists the packages named by the import paths, one per line.

The default output shows the package import path:

    code.google.com/p/google-api-go-client/books/v1
    code.google.com/p/goauth2/oauth
    code.google.com/p/sqlite

The -f flag specifies an alternate format for the list, using the
syntax of package template.  The default output is equivalent to -f
‘{{.ImportPath}}‘. The struct being passed to the template is:

    type Package struct {
        Dir           string // directory containing package sources
        ImportPath    string // import path of package in dir
        ImportComment string // path in import comment on package statement
        Name          string // package name
        Doc           string // package documentation string
        Target        string // install path
        Goroot        bool   // is this package in the Go root?
        Standard      bool   // is this package part of the standard Go library?

        Stale         bool   // would ‘go install‘ do anything for this package?

        Root          string // Go root or Go path dir containing this package

        // Source files
        GoFiles        []string // .go source files (excluding CgoFiles, TestGoF
iles, XTestGoFiles)
        CgoFiles       []string // .go sources files that import "C"
        IgnoredGoFiles []string // .go sources ignored due to build constraints
        CFiles         []string // .c source files
        CXXFiles       []string // .cc, .cxx and .cpp source files
        MFiles         []string // .m source files
        HFiles         []string // .h, .hh, .hpp and .hxx source files
        SFiles         []string // .s source files
        SwigFiles      []string // .swig files
        SwigCXXFiles   []string // .swigcxx files
        SysoFiles      []string // .syso object files to add to archive

        // Cgo directives
        CgoCFLAGS    []string // cgo: flags for C compiler
        CgoCPPFLAGS  []string // cgo: flags for C preprocessor
        CgoCXXFLAGS  []string // cgo: flags for C++ compiler
        CgoLDFLAGS   []string // cgo: flags for linker
        CgoPkgConfig []string // cgo: pkg-config names

        // Dependency information
        Imports []string // import paths used by this package
        Deps    []string // all (recursively) imported dependencies

        // Error information
        Incomplete bool            // this package or a dependency has an error
        Error      *PackageError   // error loading package
        DepsErrors []*PackageError // errors loading dependencies

        TestGoFiles  []string // _test.go files in package
        TestImports  []string // imports from TestGoFiles
        XTestGoFiles []string // _test.go files outside package
        XTestImports []string // imports from XTestGoFiles
    }

The template function "join" calls strings.Join.

The template function "context" returns the build context, defined as:

        type Context struct {
                GOARCH        string   // target architecture
                GOOS          string   // target operating system
                GOROOT        string   // Go root
                GOPATH        string   // Go path
                CgoEnabled    bool     // whether cgo can be used
                UseAllFiles   bool     // use files regardless of +build lines,
file names
                Compiler      string   // compiler to assume when computing targ
et paths
                BuildTags     []string // build constraints to match in +build l
ines
                ReleaseTags   []string // releases the current release is compat
ible with
                InstallSuffix string   // suffix to use in the name of the insta
ll dir
        }

For more information about the meaning of these fields see the documentation
for the go/build package‘s Context type.

The -json flag causes the package data to be printed in JSON format
instead of using the template format.

The -e flag changes the handling of erroneous packages, those that
cannot be found or are malformed.  By default, the list command
prints an error to standard error for each erroneous package and
omits the packages from consideration during the usual printing.
With the -e flag, the list command never prints errors to standard
error and instead processes the erroneous packages with the usual
printing.  Erroneous packages will have a non-empty ImportPath and
a non-nil Error field; other information may or may not be missing
(zeroed).

For more about build flags, see ‘go help build‘.

For more about specifying packages, see ‘go help packages‘.

 

編譯標籤

 

在原始碼裡添加標註,通常稱之為編譯標籤( build tag) ,編譯標籤是在盡量靠近原始碼檔案頂部的地方用注釋的方式添加
go build在構建一個包的時候會讀取這個包裡的每個源檔案並且分析編譯便簽,這些標籤決定了這個源檔案是否參與本次編譯

編譯標籤添加的規則(附上原文):

  1. a build tag is evaluated as the OR of space-separated options
  2. each option evaluates as the AND of its comma-separated terms
  3. each term is an alphanumeric word or, preceded by !, its negation
  • 編譯標籤由空格分隔的編譯選項(options)以"或"的邏輯關係組成
  • 每個編譯選項由逗號分隔的條件項以邏輯"與"的關係組成
  • 每個條件項的名字用字母+數字表示,在前面加!表示否定的意思

比如  https://bitbucket.org/kardianos/osext/src   這裡的 osext_procfs.go 檔案頭上的 +build 部分就是。

這裡標示 linux netbsd openbsd solaris 這些作業系統下會編譯這個檔案。

更複雜的編譯標籤 可以參考: http://blog.csdn.net/varding/article/details/12675971 

 

 

 

檔案尾碼

這個方法通過改變檔案名稱的尾碼來提供條件編譯,這種方案比編譯標籤要簡單,go/build可以在不讀取源檔案的情況下就可以決定哪些檔案不需要參與編譯

檔案命名規範可以在go/build 包裡找到詳細的說明,簡單來說如果你的源檔案包含尾碼:_$GOOS.go,那麼這個源檔案只會在這個平台下編譯,_$GOARCH.go也是如此。這兩個尾碼可以結合在一起使用,但是要注意順序:_$GOOS_$GOARCH.go,    不能反過來用:_$GOARCH_$GOOS.go

比如  https://bitbucket.org/kardianos/osext/src 這裡的檔案就是這個規則

osext_plan9.go        只會在 plan9 中編譯。

osext_windows.go   只會在windows下編譯。

 

更多請參考: http://blog.csdn.net/varding/article/details/12675971 

 

參考資料:

使用go build 進行條件編譯
http://blog.csdn.net/varding/article/details/12675971

Go按照條件編譯

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.