tinygo icon indicating copy to clipboard operation
tinygo copied to clipboard

Injecting build time variables with ldflags not working for target wasm

Open evilnoxx opened this issue 3 years ago • 3 comments
trafficstars

As the title says, setting a variable with -ldflags="-X '<.....>'" doesn't seem to work if the target is set to wasm

I've tried it with a simple example:

package main

import "fmt"

var version = "unknown"

func main() {
	fmt.Printf("%s\n", version)
}

compiled with: tinygo build -ldflags="-X 'main.version=whatever'" -target wasm

But after loading the wasm in a browser, the console shows "unknown" instead of "whatever".

The same approach to setting variables, works fine if i use -target wasi, and run the wasm with wasmedge.

Am I doing something wrong, or is this a bug?

tinygo version 0.23.0 darwin/amd64 (using go version go1.18.2 and LLVM version 14.0.0)

evilnoxx avatar Jul 11 '22 16:07 evilnoxx

It works if you remove the default value for the value. For example:

var version string

Doing this with an initializer is not currently supported.

aykevl avatar Jul 15 '22 13:07 aykevl

The variables get initialized now.

Thank you for the help.

evilnoxx avatar Jul 15 '22 17:07 evilnoxx

Is this documented sufficiently already or do we need to fix it? If the docs are up-to-date, can we close this bug?

dgryski avatar Jul 21 '22 22:07 dgryski

I don't think this is documented anywhere for TinyGo. It's just a side effect from how the x/tools/go/ssa package works and how this feature is implemented in TinyGo. Not sure what to do about it, apart from fixing this case in the compiler.

aykevl avatar Aug 21 '22 22:08 aykevl

Please see https://github.com/tinygo-org/tinygo-site/pull/357

deadprogram avatar May 18 '23 09:05 deadprogram

This is part of the v0.28 release so now closing this issue. Thanks!

deadprogram avatar Jun 14 '23 08:06 deadprogram