Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use build tags?

Tags:

go

build

go-build

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?

like image 683
Doug Avatar asked Mar 05 '13 01:03

Doug


People also ask

What is build tag?

Build Tags in Go is an identifier ( in the form of a single line comment) added to the top level of your file, which tells the Go Compiler to what to do with the file during the build process.

What is Go build?

go build command is generally used to compile the packages and dependencies that you have defined/used in your project. So how go build is executing internally, what compiler executes, which directories created or deleted; Those all questions are answered by go build command flags.


2 Answers

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".

like image 67
axw Avatar answered Sep 24 '22 09:09

axw


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.

like image 23
topskip Avatar answered Sep 22 '22 09:09

topskip