27

Does GO language have a preprocessor? When I looked up internet, there was few approaches which *.pgo convert to *.go. And, I wonder if it is doable in Go

#ifdef COMPILE_OPTION
  {compile this code ... }
#elif 
  {compile another code ...}

or, #undef in c

GoGo
  • 559
  • 3
  • 7
  • 14

3 Answers3

39

The closest way to achieve this is by using build constraints. Example:

main.go

package main

func main() {
    println("main()")
    conditionalFunction()
}

a.go

// +build COMPILE_OPTION

package main

func conditionalFunction() {
    println("conditionalFunction")
}

b.go

// +build !COMPILE_OPTION

package main

func conditionalFunction() {
}

Output:

% go build -o example ; ./example
main()

% go build -o example -tags COMPILE_OPTION ; ./example
main()
conditionalFunction
2

potentially it is possible to use Java Comment Preprocessor + maven golang plugin and get some similar behavior, in the case golang code will look like

//#if COMPILE_OPTION
 fmt.Println("Ok")
//#else
 fmt.Println("No")
//#endif

some example has been placed here https://github.com/raydac/mvn-golang/tree/master/mvn-golang-examples/mvn-golang-examples-preprocessing

Igor Maznitsa
  • 833
  • 7
  • 12
2

Note that it's possible to use any macro language as a preprocessor for go. An example would be GNU's m4 macro language.

You can then write your code in *.go.m4 files, use your build system to feed them through m4 to turn them into generated *.go files, and then compile them.

This can also be handy for writing generics.

Donovan Baarda
  • 411
  • 4
  • 5