Search code examples
goconditional-compilation

C-style conditional compilation in golang


Does golang support

#define DEBUG 

#ifdef DEBUG 
  fmt.Println("Debug message..."); 
#endif 

So I can build a debug version with zero runtime overhead?


Solution

  • Go does not have a preprocessor or a macro system. What you could do is pass in tags to go build through the -tags flag and use build constraints. To do this you would need two versions of the same source and only one would get build depending if the tag is present or not.

    Look at build constraints in https://golang.org/pkg/go/build/

    main_debug.go

    // +build debug
    
    package main
    
    import (
        "fmt"
    )
    
    func main() {
        fmt.Println("Debug build")
    }
    

    main_release.go

    // +build !debug
    
    package main
    
    import (
        "fmt"
    )
    
    func main() {
        fmt.Println("Release build")
    }
    

    Here go build would compile with main_release.go and go build -tags debug would compile with main_debug.go