Proposal Details

The main goal of this proposal is to make it easy to include C header files from other Go modules.

Similarly to ${SRCDIR}, something like ${REPODIR} could help using C/cgo headers and libraries from other Go modules. One would then be able to include a header file using:

// #cgo CFLAGS: -I${REPODIR}
// #include <github.com/someuser/modname/cgo/a_fancy_header.h> // Accessed via ${REPODIR}
import "C"

where ${REPODIR} would contain all the dependencies of the project at the correct version specified by go.mod.

Alternatively, the documentation available on Go project layout and cgo (wiki or cmd) does not seem to cover the case of projects with multiple Go modules exporting cgo code to other Go modules. At the moment, one has to rely on trials and errors to come up with a layout, what path to use in header files, etc.

Adding some guidance to https://go.dev/doc/modules/layout would help tremendously, specifically what conventions to use so that cgo can use headers and libraries from other Go modules. Perhaps better documentation can make this proposal unnecessary.

Comment From: gabyhelp

Related Issues

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

Comment From: seankhliao

I think direct access to things outside the module is generally considered out of scope and not something to encourage.

Comment From: tdegris

If a Go module exports some code with cgo, what would you recommend to access the header files generated by cgo or header files used by cgo code?

Would it be possible to update the cgo documentation mentioned above so that users know what to do and what is recommended?

Comment From: neild

I don't know if we'd want to make any change here (cgo isn't really my area), but it doesn't seem necessarily incorrect to allow one cgo-using module to include a header file from a module in its dependencies. Going to reopen this for the moment at least to allow for more discussion.

Comment From: tdegris

Unless I am mistaken, the related proposal cmd/cgo: expand $GOPATH in -I and -L directives was proposed before Go modules existed. It seems to me that Go modules now adresses all the comments in the issue.

Comment From: ianlancetaylor

REPODIR seems costly to implement.

I agree that there is something to do here, but I don't think it's that. I don't know that it can be done with documentation—that is, I don't know how to write that documentation myself—but if it can that seems appropriate.