multiple definition when using cgo

此生再无相见时 提交于 2021-01-29 09:24:12

问题


package main

/*
int add(int a, int b) {
    return a + b;
}
*/
import "C"
import "fmt"

func main() {}

func Test1() {
    fmt.Println(C.add(1, 3))
}

//export Test2
func Test2() {

}

Compile the programe:

dingrui@dingrui-PC:~/Projects/gotest/array$ go build -o libtest.so -buildmode=c-shared main.go 
# command-line-arguments
/tmp/go-build043762604/b001/_x002.o: In function `add':
./main.go:5: multiple definition of `add'
/tmp/go-build043762604/b001/_x001.o:/tmp/go-build/main.go:5: first defined here
collect2: error: ld returned 1 exit status

If I delete the "//export Test2" line, it compile successfully.


回答1:


This behavior is documented here

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.



来源:https://stackoverflow.com/questions/58606884/multiple-definition-when-using-cgo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!