Override an external package's cgo compiler and linker flags?

感情迁移 提交于 2020-12-30 06:34:08

问题


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


回答1:


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"



回答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.



来源:https://stackoverflow.com/questions/28710276/override-an-external-packages-cgo-compiler-and-linker-flags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!