如何在go build命令行中指定CFLAGS参数,而不是在go源文件中指定?

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

How to specify the CFLAGS parameter in go build command line instead of in the go source file?

问题

例如,在go文件中的MY_NUM:

//#cgo CFLAGS: -DMY_NUM=3
/*
int multiple(int x) {
    return x * MY_NUM;
}
*/
import "C"

....

但是我经常会更改MY_NUM的值。所以我想在构建命令中更改它。

我该如何在go build命令行中定义它?

英文:

For example, the MY_NUM in go file:

//#cgo CFLAGS: -DMY_NUM=3
/*
int multiple(int x) {
    return x * MY_NUM;
}
*/
import "C"

....

But I will often change the value of MY_NUM. So I want change it in build command.

How can I define it in go build command line?

答案1

得分: 1

这不完全是一个go build选项,但你可以使用CGO_CFLAGS环境变量,例如:

$ cat foo.go
package main

/*
int multiple(int x) {
        return x * MY_NUM;
}
*/
import "C"

import "fmt"

func main() {
        fmt.Println(C.multiple(2))
}
$ CGO_CFLAGS="-DMY_NUM=10" go build foo.go
$ ./foo
20
$

来源:https://pkg.go.dev/cmd/cgo

在构建时,CGO_CFLAGSCGO_CPPFLAGSCGO_CXXFLAGSCGO_FFLAGSCGO_LDFLAGS环境变量会添加到从这些指令派生的标志中。应该使用指令设置特定于包的标志,而不是使用环境变量,以便在未修改的环境中进行构建。从环境变量获取的标志不受上述安全限制的影响。

英文:

it's not exactly a go build option, but you could use the CGO_CFLAGS environment variable, e.g.:

$ cat foo.go
package main

/*
int multiple(int x) {
        return x * MY_NUM;
}
*/
import "C"

import "fmt"

func main() {
        fmt.Println(C.multiple(2))
}
$ CGO_CFLAGS="-DMY_NUM=10" go build foo.go
$ ./foo
20
$

from https://pkg.go.dev/cmd/cgo

> When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS, CGO_FFLAGS
> and CGO_LDFLAGS environment variables are added to the flags derived
> from these directives. Package-specific flags should be set using the
> directives, not the environment variables, so that builds work in
> unmodified environments. Flags obtained from environment variables are
> not subject to the security limitations described above.

huangapple
  • 本文由 发表于 2021年12月19日 21:53:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/70412041.html
匿名

发表评论

匿名网友

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

确定