golang/go

cmd/cgo: link error when using pointers to static C functions

Open

#19,836 opened on Apr 4, 2017

View on GitHub
 (5 comments) (1 reaction) (0 assignees)Go (19,008 forks)batch import
NeedsFixcompiler/runtimehelp wanted

Repository metrics

Stars
 (133,883 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

If I try to pass a pointer to a static C function, I get a link error.

cgocallback/main.go:

package main

/*
#include <stdio.h>

static void invoke(void (*f)()) {
	f();
}

static void print_hello() {
	printf("Hello, !");
}

typedef void (*closure)();  // https://golang.org/issue/19835
*/
import "C"

func main() {
	C.invoke(C.closure(C.print_hello))
}
bcmills:~$ go build cgocallback
# cgocallback
/tmp/go-build059026917/cgocallback/_obj/_cgo_main.o:(.data.rel+0x0): undefined reference to `print_hello'
collect2: error: ld returned 1 exit status

The workaround is to use external linkage for functions used as function pointers, but in some cases that means I have to use more verbose names to avoid collisions.

(Possibly related to #19835.)

bcmills:~$ go version
go version devel +2bbfa6f746 Thu Mar 9 15:36:43 2017 -0500 linux/amd64
bcmills:~$ $(go env CC) --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4

Contributor guide