32

I need to be able to build different versions of a go application; a 'debug' version and a normal version.

This is easy to do; I simply have a const DEBUG, that controls the behaviour of the application, but it's annoying to have to edit the config file every time I need to swap between build types.

I was reading about go build (http://golang.org/pkg/go/build/) and tags, I thought perhaps I could do this:

config.go:

// +build !debug
package build
const DEBUG = false

config.debug.go:

// +build debug
package build
const DEBUG = true

Then I should be able to build using go build or go build -tags debug, and the tags should exclude config.go and include config.debug.go.

...but this doesn't work. I get:

src/build/config.go:3: DEBUG redeclared in this block (<0>) previous declaration at src/build/config.debug.go:3

What am I doing wrong?

Is there another and more appropriate #ifdef style way of doing this I should be using?

0

3 Answers 3

32

See my answer to another question. You need a blank line after the // +build line.

Also, you probably want the ! in config.go, not in config.debug.go; and presumably you want one to be "DEBUG = false".

1
22

You could use compile time constants for that: If you compile your program with

go build -ldflags '-X main.DEBUG=YES' test.go

the variable DEBUG from package main will be set to the string "YES". Otherwise it keeps its declared contents.

package main

import (
    "fmt"
)

var DEBUG = "NO"

func main() {
    fmt.Printf("DEBUG is %q\n", DEBUG)
}

Edit: since Go 1.6(?) the switch is -X main.DEBUG=YES, before that it was -X main.DEBUG YES (without the =). Thanks to a comment from @poorva.

2
  • 1
    Is this possible for non-string data? Oct 6, 2014 at 13:59
  • @MattJoiner didn't test everything but it is possible with ints. Feb 9, 2015 at 2:18
4

As of Go 1.17, build tags can be specified with the new //go:build syntax.

As for the placement of the //go:build directive, the new design states:

Constraints may appear in any kind of source file (not just Go), but they must appear near the top of the file, preceded only by blank lines and other // and /* */ comments. These rules mean that in Go files a build constraint must appear before the package clause.

So you still need to leave a blank line between the //go:build directive and the package statement, otherwise it could be parsed as package documentation, however now:

  • the compiler will reject misplaced directives
  • running go fmt will automatically fix misplaced directives

For example running go fmt on (no blank line):

//go:build foo
package main

import "fmt"

func main() {
    fmt.Println("Hello world")
}

gives (with blank line):

//go:build foo

package main

import "fmt"

func main() {
    fmt.Println("Hello world")
}

See also this answer for further details about what changes with the new syntax.

Not the answer you're looking for? Browse other questions tagged or ask your own question.