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?
CodePudding user response:
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.