douzheyo2617
2015-06-15 13:35
浏览 368
已采纳

Go上是否存在诸如#ifdef之类的C ++宏之类的东西,因此我可以选择基于标记构建什么?

I need to build in go for linux and windows with different packages same file on windows I need to import github.com/hashicorp/go-syslog and on linux import log/syslog

and inside code in file I have to use syslog.ALERT or gsyslog.ALERT depending on os. Does exist on Go something like macros in C++ like #ifdef so I can choose what to build based on flag ? How to achieve this without, same file to have different content for build based on OS ?

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

我需要在Linux和Windows中使用不同的包相同的文件构建Windows \非Windows我需要 导入github.com/hashicorp/go-syslog 并在linux 上导入log / syslog

和文件中的内部代码我必须使用 syslog.ALERT gsyslog.ALERT (取决于操作系统)。 在 Go 上是否存在诸如 #ifdef 之类的 C ++ 中的宏之类的东西,所以我可以选择基于标记构建什么? 如何在没有相同文件的情况下基于OS构建具有相同内容的不同文件?

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

2条回答 默认 最新

  • dounue1965 2015-06-15 13:44
    已采纳

    This is what build tags are for:

    A build constraint, also known as a build tag, is a line comment that begins

    // +build
    

    that lists the conditions under which a file should be included in the package. Constraints may appear in any kind of source file (not just Go), but they must appear near the top of the file, preceded only by blank lines and other line comments. These rules mean that in Go files a build constraint must appear before the package clause.

    Another way to distinguish OS/arch at runtime is to use runtime's GOOS and GOARCH constants:

    GOARCH is the running program's architecture target: 386, amd64, or arm.

    GOOS is the running program's operating system target: one of darwin, freebsd, linux, and so on.

    已采纳该答案
    打赏 评论
  • duankong8998 2015-06-15 13:45

    You can work with build tags as described here.

    In a nutshell, insert a comment like

    // +build linux
    

    at the top of your file and this file will only build on linux. Accordingly

    // +build windows
    

    will only build the file on windows.

    Be sure to put a blank line after the afforementioned comment. Read this for reference.

    打赏 评论

相关推荐 更多相似问题