---
id: 1872edeaa3c5fc09a1eba338cf2b01b1
author: wHoIsDReAmer
title: 'Go Compile-Time Variable Injection: Using go build -ldflags -X'
description: This document explains how to inject Go string variable values at compile time without an external .env file, by using the go build -ldflags "-X" linker flag and specifying the package symbol path.
language: en
date: 2025-06-01T15:56:46.352281271Z
path: /blog/posts/compile-time-variable-injection-of-go-z5420556c
category: api
---

## Background

While working on a company project recently, I looked into whether there is a way to inject variables at compile time without a `.env` file.
I thought this would be very convenient, since only a single file would be needed without any `.env` or multiple config files.

At first, I searched for a `go:generate` CLI or something similar that generates a constants file based on `.env`, but I could not find one.

However, if I were going to do that, I could just modify the constants directly without bothering to run a generator, and I found that there is a way to inject values at compile time, similar to the `include_bytes!` macro in Rust.

## Compile-Time Variable Injection

The usage is simple.

```go
package main

import "fmt"

var Foo string

func main() {
    fmt.Println(Foo)
}
```

Given code like the above, you can inject a value at build time as follows.

```bash
go build -ldflags="-X 'main.Foo=bar'"
```

By passing the argument through ldflag, the value `bar` is injected into the `Foo` variable at compile time during the build. It is simple.

If there are variables or packages with the same name in multiple places in the project, you can **specify the package path**.

```go
// github.com/myproject/config/config.go
package config

var Version string

// github.com/myproject/internal/config/config.go
package config

var BuildTime string
```

In such cases, you can inject them separately as follows:

```bash
go build -ldflags="-X 'github.com/myproject/config.Version=v1.0.0' -X 'github.com/myproject/internal/config.BuildTime=2025-05-27'"
```

Even when multiple variables exist in the same package, you simply pass additional arguments.

```bash
go build -ldflags="-X 'main.Version=v1.0.0' -X 'main.BuildTime=2025-05-27' -X 'main.GitCommit=abc123'"
```

The characteristics are as follows:

- **The variable does not need to be public**: variables starting with a lowercase letter can also be injected
- **Only string type is supported**: other types are not supported

## References

- [https://stackoverflow.com/questions/47509272/how-to-set-package-variable-using-ldflags-x-in-golang-build](https://stackoverflow.com/questions/47509272/how-to-set-package-variable-using-ldflags-x-in-golang-build)
