Previous: C Type Interoperability, Up: C Interoperability


3.2 Function Names

Go code can call C functions directly using a Go extension implemented in gccgo: a function declaration may be preceded by a comment giving the external name. The comment must be at the beginning of the line and must start with //extern. This must be followed by a space and then the external name of the function. The function declaration must be on the line immediately after the comment. For example, here is how the C function open can be declared in Go:

     //extern open
     func c_open(name *byte, mode int, perm int) int

The C function naturally expects a nul terminated string, which in Go is equivalent to a pointer to an array (not a slice!) of byte with a terminating zero byte. So a sample call from Go would look like (after importing the os package):

     var name = [4]byte{'f', 'o', 'o', 0};
     i := c_open(&name[0], os.O_RDONLY, 0);

Note that this serves as an example only. To open a file in Go please use Go's os.Open function instead.

The name of Go functions accessed from C is subject to change. At present the name of a Go function that does not have a receiver is prefix.package.Functionname. The prefix is set by the -fgo-prefix option used when the package is compiled; if the option is not used, the default is simply go. To call the function from C you must set the name using the gcc __asm__ extension.

     extern int go_function(int) __asm__ ("myprefix.mypackage.Function");