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

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命令行中定义它?

它不完全是一个 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

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.