在Go包中持久设置CGO_CFLAGS的方法是什么?

huangapple go评论94阅读模式
英文:

Setting CGO_CFLAGS persistently in a Go package?

问题

我的Go包含一个使用需要特定CFLAGS设置的库的.c文件。在命令行中使用"go install"时,我可以使用所需的标志指定CGO_CFLAGS,一切正常。然而,我希望能够让其他人"go get"我的包并在不传递任何额外命令行参数的情况下构建它。

Go打包系统是否提供了一个地方,我可以在其中放置一些配置,以指定在"go install"包时始终需要的一些参数?

(我知道可以在Go源文件中使用#cgo CFLAGS:指令,但请记住,在我的包中我有一个.c源文件,因此需要将CGO_CFLAGS设置为整个构建过程)

英文:

My Go package includes a .c file that uses a library which needs certain CFLAGS set. On the command line to "go install" I can specify CGO_CFLAGS with the needed flags, and everything works. However, I would like to make it so that someone can "go get" my package and build it without passing any extra command line arguments.

Does the Go packaging system provide a place where I could put some config like this, to specify some arguments that are always needed when go installing a package?

(I'm aware of doing #cgo CFLAGS: directives in Go source files, but recall that in my package I have a .c source file so need the CGO_CFLAGS setting to the overall build process)

答案1

得分: 7

cgo在构建过程中将你的*#cgo CFLAGS:提取到一个环境变量中(在go build中传递"-x"标志)。如果你运行go install -x *,你会看到它会遵循你在Go库中指定的cflags/ldflags。换句话说,只需在你的Go文件中指定它们就可以工作。

英文:

cgo extracts your #cgo CFLAGS: to an environment variable during build (pass "-x" flag to go build). If you go install -x <youpack> you see that it honors your cflags/ldflags specified in your Go library. In other words, it should work to just specify them in your Go files.

答案2

得分: 1

为了使用您的C函数,您仍然需要在.go文件中混合一些cgo代码,在这些文件中只需声明您的标志,例如:

test.go:

package main

import "fmt"

/*
#cgo CFLAGS: -DTEST
#include <stdio.h>
extern void ACFunction();
*/
import "C"

//export AGoFunction
func AGoFunction() {
        fmt.Println("AGoFunction()")
}

func main() {
        C.ACFunction()
}

test.c:

#include "_cgo_export.h"
void ACFunction() {
#ifdef TEST
        printf("ACFunction()\n");
#endif
        AGoFunction();
}

将这些文件放在同一个目录中,go build将会使用test.go中定义的标志,并在构建test.c时应用它们。

英文:

In order to use any of your C functions you still have to mix some cgo into your .go files, in those files just declare your flags, for example:

test.go:

package main

import &quot;fmt&quot;

/*
#cgo CFLAGS: -DTEST
#include &lt;stdio.h&gt;
extern void ACFunction();
*/
import &quot;C&quot;

//export AGoFunction
func AGoFunction() {
        fmt.Println(&quot;AGoFunction()&quot;)
}

func main() {
        C.ACFunction()
}

test.c:

#include &quot;_cgo_export.h&quot;
void ACFunction() {
#ifdef TEST
        printf(&quot;ACFunction()\n&quot;);
#endif
        AGoFunction();
}

Putting these in the same directory will make go build pickup the flags defined in test.go and apply them when building test.c.

huangapple
  • 本文由 发表于 2014年4月8日 00:09:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/22917602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定