duan0065626385 2014-09-12 16:31
浏览 51
已采纳

Go的链接器可以覆盖初始化的变量吗

From ld's docs:

-X symbol value

Set the value of an otherwise uninitialized string variable. The symbol name should be of the form importpath.name, as displayed in the symbol table printed by "go tool nm".

So this is pretty cool. It allows you to do stuff like this:

package main

import "fmt"

var version string

func main() {
    fmt.Println(version)
}

Compile with: go build -ldflags '-X main.version 42' ...

I have two question about his feature. First of all it also works for initialized strings (e.g. var version = "bad build") even though the documentation specifically says "otherwise uninitialized string variable".

The seconds question is about spaces. My Makefile contains the following lines:

GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null)
GIT_COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null)

LDFLAGS := '-X main.version "$(GIT_BRANCH) $(GIT_COMMIT)"'

The documentation for the go command says:

-ldflags 'flag list'

So they're using single quotes for all linker flags. But what about a string containing spaces as symbol for the -X flag? The double-quotes work just fine, so do escaped single-quotes btw., I'm just not sure I can rely on all that to work consistently given the docs not mentioning any of it.

Clarification of the first question:

Go zero-initializes all vars.

The documentation says: -X symbol value Set the value of an otherwise uninitialized string variable [...].

Does this mean:

var foo string // only this one?
var bar = "bar" // or this one too, maybe
  • 写回答

1条回答 默认 最新

  • dongsu7049 2014-09-12 17:45
    关注

    The quotes are handled by the shell (or make), so yes it's consistent.

    The calling program populates go's args.

    //edit

    To use a default version you can use something like this:

    var version string
    
    func init() {
        if len(version) == 0 {
            version = "master"
        }
    }
    

    //edit 2

    From the spec:

    When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名