Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional compilation in Go

Tags:

go

cgo

I'm trying to write a Go wrapper using CGo for ENet.

When I tried to compile my wrapper on a Mac the library was older and had a slightly different interface. 99% of the code is the same just a few C calls need to change.

What is the best practice for dealing with a problem like this in Go?
Is there some way to do conditional compilation or conditional imports?

like image 493
deft_code Avatar asked Jun 21 '12 16:06

deft_code


People also ask

What is meant by conditional compilation?

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.

Does go compile to an executable?

While the go run command is a useful shortcut for compiling and running a program when you're making frequent changes, it doesn't generate a binary executable.

What is conditional compilation in C?

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.

How do I compile a go program?

To run a Go program (assuming you have installed Go on your system), you need to instruct the Go compiler to compile and run a program using go run command with the relative or absolute path of the Go program file.


1 Answers

Separate out the platform-specific stuff into a separate file, e.g. stuff.go

Now replace stuff.go with versions for the different platforms, like stuff_darwin.go (for Mac), stuff_windows.go, stuff_linux.go, etc.

If a file has a suffix like that, the go command will compile it only on the platform specified.

like image 55
andybalholm Avatar answered Sep 22 '22 13:09

andybalholm