7

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?

deft_code
  • 57,255
  • 29
  • 141
  • 224

2 Answers2

18

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.

andybalholm
  • 15,395
  • 3
  • 37
  • 41
  • 8
    Documented under "Build Constriants" in the [overview](http://golang.org/pkg/go/build/#overview) of package go/build. – Sonia Jun 21 '12 at 18:06
  • Great info and absolutely the right answer for OS incompatibilities. However the root of my problem is differing library versions so I went with the answer that addressed that directly. – deft_code Jun 26 '12 at 18:09
2

Go does not have conditional compilation or conditional imports. Handle the type differences in C code.

Are the [Go] authors opposed to preprocessing?

peterSO
  • 158,998
  • 31
  • 281
  • 276
  • Go actually does have conditional compilation using filename suffixes as andyBallholm's answer demonstrates. – Jeremy Wall Jun 26 '12 at 03:55
  • 1
    Downvoters gonna hate :). Seriously though, @peterSO has the correct answer for my particular problem. Turns out the Mac thing is a red herring. The real issue is with library versions, which can only be detected as a `#define` in the header files. `_darwin.go` or `_linux.go` would only mask the problem until one of them updated their ENet library with a backward incompatible change. – deft_code Jun 26 '12 at 18:06