gonum and Cgo

196 views
Skip to first unread message

George Armhold

unread,
Apr 29, 2016, 10:06:43 AM4/29/16
to gonum-dev
Thanks to some kind help from /u/howeman on reddit I was able to roughly triple the performance of my code by building OpenBLAS and then adding blas64.Use(cgo.Implementation{}) to my code. I peeked into that call, and I see that it merely sets a package variable, that presumably is used at runtime to pick the implementation.

My question is: how and when does this tie my project to Cgo? Was the C linkage was already present due to my import of the gonum libs, regardless of my setting that variable? I'm relatively new to Go, and thus far my understanding has been that Cgo gets involved whenever you use a library that has C bindings. Which would mean that merely using gonum at all forces you to use Cgo... is that correct?

My program is tiny, but I want to understand the implications of that. 

Thanks.

Brendan Tracey

unread,
Apr 29, 2016, 10:56:27 AM4/29/16
to gonum-dev
It is not true that using gonum at all forces Cgo. If CGO_LDFLAGS is not set and you don't import any of the cgo packages, the c libraries are not associated with your program.

I believe that the cgo linking happens at compile time, and is solely dependent on the value of CGO_LDFLAGS. That is, even if you don't import the cgo packages, but CGO_LDFLAGS is set, the c packages are still linked in with the executable. Traditionally I have had CGO_LDFLAGS set in my .bash_proflie, but I've been considering changing to just enabling per-compilation.

Dan Kortschak

unread,
Apr 29, 2016, 5:49:01 PM4/29/16
to Brendan Tracey, gonum-dev
If the blas64.Use(cgo.Implementation{}) call is not made the blas/cgo package is not imported (unless direct calls the blas/cgo methods are made). If it's not imported, it's not linked.

Other cgo-dependent (we really should sort out our naming of this - here I mean cmd/cgo) code such as in os and net will be linked in if used.

George Armhold

unread,
Apr 30, 2016, 7:12:29 AM4/30/16
to gonum-dev, tracey....@gmail.com
I get it now. It's the import of github.com/gonum/*/cgo that causes the linkage, because those package are otherwise isolated from the rest of the gonum libs. I was failing to notice the package boundaries (which I'm sure is the whole point- keep it isolated).

Thanks (both of you) for the explanation.
Reply all
Reply to author
Forward
0 new messages