Search code examples
gostatic-librariesldcgo

How can I link a Go static library to a C program


I'm trying to call a Go function from a C program. I have built a static library from my Go source, however, ld is unable to find the function I want to call from the C program.

Go code:

package main

import "fmt"
import "C"

// (this can be called anything)
// export goCallbackHandler
func goCallbackHandler() C.int {
    i := Hello()
    return C.int(i)
}

func Hello() int {
    fmt.Println("Hello, world!")
    return 0
}

func main() {
}

C code: (main.c)

#include "binding.h"

int main() {
     // Call the function from the binding
     return goCallbackHandler();
}

(binding.h)

extern int goCallbackHandler();

I can build the library successfully with go build -o libhello.a -buildmode=c-archive hello.go. However, when I then try to build the C part with gcc -o hello main.c -L. -lhello I get the error

main.c:(.text+0xe): undefined reference to `goCallbackHandler'
collect2: error: ld returned 1 exit status

from ld


Solution

  • Whitespace matters: the export comment needs to be //export, not // export. Your version doesn't actually export anything. With the export comment fixed to be //export goCallbackHandler, it works as expected.