Search code examples
goheaderincludecgo

How to include headers from a third party package in Go?


Let's supose my package workspace has github.com/yada/yada third party package. Inside this package there is a yoda.go.h header I would like to reuse (not sure if it's a good idea, but that's a hole new question). How do I import the header from a dependecy package into my own package?

package main

// #cgo pkg-config: my-dep other-dep
// #include <someHeader.h>
// #include <otherHeader.h>
// #include github.com/yada/yada/yoda.go.h // doesn't work :(
import "C"

Apart from being a good idea or not, I still would like to know if it's possible.

PS: If you think it's really a bad idea, what should I do instead?


Solution

  • Use CGO CFLAGS directive to reference additional include path.

    //#cgo CFLAGS: -I $GOPATH/src/github.com/yada/yada/
    ...
    //#include "yoda.go.h"
    import "C"
    

    CORRECTION:

    The go tool does not expand $GOPATH variable during build. Instead, the full path should be used there. Corrected code:

    //#cgo CFLAGS: -I /full/path/to/src/github.com/yada/yada/
    //#include "yoda.go.h"