-
Notifications
You must be signed in to change notification settings - Fork 18.1k
cmd/compile: initialization optimization fails when using -ldflags=-X=VAL #28969
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This looks like an issue in It would be unfortunate to lose this optimization because |
I'd document it as a limitation of |
I'm sort of OK with a doc change, but what would that doc change be? We need a simple guideline here that won't confuse people. |
Kind of a big hammer, but this optimization does not apply cross-package. We could recommend that all |
I am also thinking about this option to solve my problem @randall77 |
I suppose we could make it a compiler flag also, but it has to stay as a linker flag since the point is to set the value at link time. You don't want to have to rebuild your entire world to change a link-time variable value. |
I see, would another option be to provide a compile option to disable |
The above problem is easily solved by moving the struct inside var version = "dev"
var versions = struct {
API string
Code string
}{}
func main() {
fmt.Println(version)
versions = struct {
API string
Code string
}{"0.1.0", version}
fmt.Println(versions)
} I vote to just document it and keep it at that. Something in the lines of - "Use the -X linker flag only to assign values to global variables. If there are expressions reading from that variable, the compiler might replace the variable with the actual value, preventing the replacement from happening." |
And presumably also a cmd/go flag, which would then manage passing it appropriately to the compiler and linker? I suspect that this is one of the primary uses of |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
yes, tested with
go version go1.11.2 darwin/amd64
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I narrowed down the problem to a simple go program:
Then build it using the specific flag described in the toolchain tricks,
go build -o test -ldflags "-X main.version=1.0.0" .
What did you expect to see?
When running
./test
I would expect to get an output ofWhat did you see instead?
An output of
I suspect this is related to when
main.version
is evaluated, using ldflags makes the version resolved at link time, where the compiler may have already inlined its use and thus remove the reference used by the linkerThe text was updated successfully, but these errors were encountered: