Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Preprocessor like C-style compile switch

Tags:

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

like image 608
GoGo Avatar asked Apr 18 '16 20:04

GoGo


People also ask

Does Golang have preprocessor?

It turns out that, yes, even though Go does not have macros, or a preprocessor, Go does indeed support pragmas. They are implemented by the compiler as comments. Just to drive home the point, they're actually called pragmas in the source of the Go compiler.

Does Golang have macros?

Luckily, Go does not support macros. There are two venues in Go to implement what is done using macros in other programming languages: "Meta-programming" is done using code generation.

How is Golang compiled?

Go is a compiled language. This means we must run our source code files through a compiler, which reads source code and generates a binary, or executable, file that is used to run the program. Examples of other popular compiled languages include C, C++, and Swift.


1 Answers

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
like image 160
Tim Cooper Avatar answered Sep 30 '22 08:09

Tim Cooper