dpnvrt3119
2016-08-15 07:26
浏览 84
已采纳

Golang中的C样式条件编译

Does golang support

#define DEBUG 

#ifdef DEBUG 
  fmt.Println("Debug message..."); 
#endif 

So I can build a debug version with zero runtime overhead?

图片转代码服务由CSDN问答提供 功能建议

是否支持golang

  #define DEBUG 
 
  #ifdef调试
 fmt.Println(“调试消息...”);  
#endif 
   
 
 

这样我可以以零的运行时间开销来构建调试版本吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyi3767 2016-08-15 08:02
    已采纳

    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

    打赏 评论
  • dongzhi5386 2018-08-20 11:36

    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:

    1. You can't write a go function named "define" or "ifndef" etc which will be translated into Macro by m4.
    2. If you have a lot of files you may want to improve your Makefile.
    3. You may want to study m4 which is a little difficult and complicated.
    打赏 评论

相关推荐 更多相似问题