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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With