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 ?
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.
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.
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