Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple definition when using cgo

Tags:

go

cgo

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.

like image 343
dingrui Avatar asked Apr 13 '26 20:04

dingrui


1 Answers

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.

like image 156
Mohammad Fahim Abrar Avatar answered Apr 16 '26 01:04

Mohammad Fahim Abrar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!