Does golang support
#define DEBUG #ifdef DEBUG fmt.Println("Debug message..."); #endif
So I can build a debug version with zero runtime overhead?
Conditional compilation is the process of selecting which code to compile and which code to not compile similar to the #if / #else / #endif in C and C++. Any statement that is not compiled in still must be syntactically correct. Conditional compilation involves condition checks that are evaluable at compile time.
Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.
Conditional Compilation: Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation of some specific part of the program based on some conditions.
The $ELSE statement is used in conjunction with the $IF statement to control conditional compilation. The $END statement is used in conjunction with the $IF statement to control conditional compilation. A $IF statement provides the means whereby selected parts of the source text are not included in the compilation.
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
if you work on linux or Mac , you can try the "m4" command.This command is a macro processor which just fits this issue.
Writing a Makefile to run the m4 command before "go build" can do the same as using "go build -tags ..." and support more customization and of course, save your work.
for example:
write these within your go file(such as main.go):
define(DEBUG) ifdef(`DEBUG', fmt.Println("Debug message..."); )
write these within your Makefile file:
all:*.go mv main.go main.go.bak m4 main.go.bak > main.go go build mv main.go.bak main.go
then run "make".
Disadvantage:
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