英文:
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 install
ing 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
英文:
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 "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();
}
Putting these in the same directory will make go build
pickup the flags defined in test.go and apply them when building test.c.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论