You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
// #include <stdio.h>//// extern int go_test_func(int c1, int c2);//// int c_test_func(int c1, int c2)// {// return go_test_func(c1,c2);// }import"C"import (
"fmt"
)
//export go_test_funcfuncgo_test_func(c1, c2 C.int) C.int {
returnc1+c2
}
funcmain() {
fmt.Printf("Result: %d\n", C.c_test_func(2, 2))
}
What did you expect to see?
Successfully built binary
What did you see instead?
go build -o cgo_test cgo.go
# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
/usr/bin/ld: /tmp/go-link-644125076/000001.o: in function `c_test_func':
/home/sbezverk/projects/go/workspace/cgo/cgo.go:8: multiple definition of `c_test_func'; /tmp/go-link-644125076/000000.o:/tmp/go-build/cgo.go:8: first defined here
collect2: error: ld returned 1 exit status
Further investigation:
After looking in cgo generated files, I found that in fact function “c_test_func” is defined in 2 places.
1: ./cgo.cgo2.c:29: int c_test_func(int c1, int c2)
Using //export in a file places a restriction on the preamble: since it is copied into two different C output files, it must not contain any definitions, only declarations. If a file contains both definitions and declarations, then the two output files will produce duplicate symbols and the linker will fail. To avoid this, definitions must be placed in preambles in other files, or in C source files.
This is an unfortunate limitation. One workaround is to define c_test_func as a weak or static function.
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
go build -o cgo_stubs cgo.go
The following go code:
What did you expect to see?
Successfully built binary
What did you see instead?
Further investigation:
After looking in cgo generated files, I found that in fact function “c_test_func” is defined in 2 places.
1: ./cgo.cgo2.c:29: int c_test_func(int c1, int c2)
#line 3 "/nobackup/sbezverk/projects/go/worspace/cgo_test/cgo.go"
#include <stdio.h>
extern int go_test_func(int c1, int c2);
int c_test_func(int c1, int c2)
{
return go_test_func(c1,c2);
}
2: ./_cgo_export.h:27: int c_test_func(int c1, int c2)
#line 3 "cgo.go"
#include <stdio.h>
extern int go_test_func(int c1, int c2);
int c_test_func(int c1, int c2)
{
return go_test_func(c1,c2);
}
_cgo_export.h is included in ./_cgo_export.c:4:#include "_cgo_export.h". Making it a second definition of the same function.
The text was updated successfully, but these errors were encountered: