12

Let's say I want to use some awesome go package. I can include it by:

import "github.com/really-awesome/project/foobar"

And inside that project's foobar.go file, it defines some cgo instructions like:

#cgo windows CFLAGS: -I C:/some-path/Include
#cgo windows LDFLAGS: -L C:/some-path/Lib -lfoobar

But if I have that foobar C dependency installed somewhere else, I would really need those lines to say:

#cgo windows CFLAGS: -I C:/different-path/Include
#cgo windows LDFLAGS: -L C:/different-path/Lib -lfoobar

Is there a way to override or trump where cgo is looking for these dependencies? Right now my fix is to manually edit those two lines after running go get ./... which will fetch the github.comreally-awesome/project/foobar code.

NOTE: I'm using the MinGw compiler, though I doubt that matters.

update:

I have tried adding flags to go build to no avail:

go build -x -gcflags="-I C:/different/include -L C:/different-path/lib -lfoobar"
go build -x -ccflags="-I C:/different/include" -ldflags="-L C:/different-path/lib -lfoobar"

With the -x argument I see the printout of flags and they don't include the ones I am setting on the command line. Perhaps the #cgo CFLAGS/LDFLAGS statements at the top of the external go package squash what I am telling it to use...

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
jCuga
  • 1,523
  • 3
  • 16
  • 28
  • May be simplest, though a bit of a sad hack, to vendor the package with `godep`, `nut`, or some such tool and edit the build flags in your version. (It's common to vendor anyway, so you only get upgrades when you want them.) Possible you could pass Go the env var `CC=some_batchfile.bat` (or CXX= if a C++ compiler is being invoked) and make that file substitute in the params you want, but that's almost too painful even if it works. (With vendoring, at least the flow for your changes is similar to one others are already doing for dependency management.) – twotwotwo Feb 27 '15 at 23:55
  • fork the project, change the source, go get the forked repo :) – Jiang YD May 22 '15 at 01:21

2 Answers2

8

You can do this by setting the CGO_CPPFLAGS and CGO_LDFLAGS environment variables.

For example, on my MacBook, Homebrew is installed in ~/.homebrew (instead of /usr/local), so when I try to go get packages with native bindings they can't find the headers and libs.

To fix that I added these two lines to my ~/.zshenv file:

export CGO_CPPFLAGS="-I $BREW_HOME/include"
export CGO_LDFLAGS="-L $BREW_HOME/lib"
David E
  • 111
  • 1
  • 6
2

This is kind of the role filled by #cgo pkgconfig: foobar. If the library had been written that way, it would pick up the correct paths from foobar's pkgconfig definition.

I realise its not a direct answer to the question, and that pkgconfig isn't exactly a native windows tool... I'd be interested to hear if any other solutions exist.

sqweek
  • 1,129
  • 9
  • 12