dongxunhua2054 2014-10-29 03:00
浏览 103
已采纳

有条件地为x86和mips构建go源码

I have some go sources that are exclusively built for mips. I'm trying to get them to compile on x86 so as to run select, non-architecture-specific code on x86 as well. My sources are organized as below:

ipmi.go: # Only builds on mips.

package main

import (
    "foo"
    "bar"
)

/*
#cgo LDFLAGS: -lfreeipmi
#define FOO 1
some c code
*/

import C
// go code
func gofunc1() {
}

func gofunc2() {
}
// more go code

hardware.go: # All go code

package main
import (
         "lots"
          "of"
          "libs"
        )

func main() {
    // some go code
    ret1 = gofunc1() 
    ret2 = gofunc1() 

    // Use ret1 and ret2 to do something else.
    // more go code
}

What's the best way to enable building these sources on x86?

I added the following to ipmi.go to restrict the arch on which it is built:

// +build linux,mips,cgo

hardware.go still fails to compile since it calls gofunc1() and gofunc2(). Since hardware.go will always need to call gofunc1() and gofunc2(), I can't think of any way to conditionally compile these sources for x86. Any inisghts will be helpful.

Thanks

  • 写回答

1条回答 默认 最新

  • dongyan6503 2014-10-29 05:48
    关注

    Package build

    Build Constraints

    A build constraint, also known as a build tag, is a line comment that begins

    // +build
    

    that lists the conditions under which a file should be included in the package. Constraints may appear in any kind of source file (not just Go), but they must appear near the top of the file, preceded only by blank lines and other line comments. These rules mean that in Go files a build constraint must appear before the package clause.

    To distinguish build constraints from package documentation, a series of build constraints must be followed by a blank line.

    To build a file only when using cgo, and only on Linux and OS X:

    // +build linux,cgo darwin,cgo
    

    Such a file is usually paired with another file implementing the default functionality for other systems, which in this case would carry the constraint:

    // +build !linux,!darwin !cgo
    

    Follow the suggestion in the documentation. For example,

    hardware.go:

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println(ipmi())
    }
    

    ipmi.go:

    // +build linux,mips,cgo
    
    package main
    
    func ipmi() string { return "mips" }
    

    ipmi_not.go:

    // +build !linux !mips !cgo
    
    package main
    
    func ipmi() string { panic("not implemented") }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?