GoGo
GoGo

Reputation: 639

Golang Preprocessor like C-style compile switch

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

Upvotes: 31

Views: 15851

Answers (3)

Donovan Baarda
Donovan Baarda

Reputation: 481

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.

Upvotes: 3

Igor Maznitsa
Igor Maznitsa

Reputation: 873

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

Upvotes: 2

user142162
user142162

Reputation:

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

Upvotes: 44

Related Questions