ldflags -X

568 views
Skip to first unread message

Stephen Illingworth

unread,
Nov 8, 2023, 7:35:29 AM11/8/23
to golang-nuts
Hello,

I'm trying to use the -X ldflag to set a string at compile time. I can do this successfully if the string is in the main package but it does not work if the string is in a subpackage.

For illustration purposes, I have prepared a simple test project


The build.sh file contains the build string. It contains one useful line, which I'll repeat it here:

    go build -ldflags "-X 'main.A=foo' -X 'sub.B=bar'"

When built, the main function will print out the A string correctly but the B string is unset.

What am I doing wrong?

Regards
Stephen

Jan Mercl

unread,
Nov 8, 2023, 7:51:49 AM11/8/23
to Stephen Illingworth, golang-nuts
The second -X flag does not have the documented form, see https://pkg.go.dev/cmd/link.

jnml@3900x:~/src/x/ldflags_X_test$ ls -l
total 16
-rwxr-xr-x 1 jnml jnml  101 Nov  8 13:47 build.sh
-rw-r--r-- 1 jnml jnml   55 Nov  8 13:47 go.mod
-rw-r--r-- 1 jnml jnml  144 Nov  8 13:47 main.go
drwxr-xr-x 2 jnml jnml 4096 Nov  8 13:47 sub
jnml@3900x:~/src/x/ldflags_X_test$ git diff
diff --git a/build.sh b/build.sh
index db86e35..0185e5e 100755
--- a/build.sh
+++ b/build.sh
@@ -1,3 +1,3 @@
 #!/bin/bash
 
-go build -ldflags "-X 'main.A=foo' -X 'sub.B=bar'"
+go build -ldflags "-X 'main.A=foo' -X 'github.com/JetSetIlly/ldflags_X_test/sub.B=bar'"
jnml@3900x:~/src/x/ldflags_X_test$ ./build.sh && ./ldflags_X_test
foo
bar
jnml@3900x:~/src/x/ldflags_X_test$


Message has been deleted

Stephen Illingworth

unread,
Nov 8, 2023, 10:01:29 AM11/8/23
to golang-nuts
I would have expected the "main.A" string to require the same form. But either way, that's the correct solution.

Thanks.



Jan Mercl

unread,
Nov 8, 2023, 10:42:25 AM11/8/23
to Stephen Illingworth, golang-nuts
On Wed, Nov 8, 2023 at 4:01 PM Stephen Illingworth
<stephen.i...@gmail.com> wrote:

> I would have expected the "main.A" string to require the same form. But either way, that's the correct solution.

It is the correct form. Package main cannot be imported and has a
special import path. Though I don't know where it is documented.

Stephen Illingworth

unread,
Nov 8, 2023, 10:48:06 AM11/8/23
to golang-nuts
Yes. I agree that it's correct given the general rules.
Reply all
Reply to author
Forward
0 new messages