Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does exist on Go something like macros in C++ like #ifdef so I can choose what to build based on flag?

Tags:

go

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 ?

like image 347
Black Obama Avatar asked Jun 15 '15 13:06

Black Obama


2 Answers

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.

like image 166
Ainar-G Avatar answered Oct 13 '22 15:10

Ainar-G


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.

like image 29
Peter Brennan Avatar answered Oct 13 '22 13:10

Peter Brennan