使用cgo时的多重定义 [英] multiple definition when using cgo

查看:266
本文介绍了使用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() {

}

编译程序:

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

如果我删除"//export Test2"行,则编译成功.

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

推荐答案

这里

在文件中使用//export会对序言进行限制:由于将其复制到两个不同的C输出文件中,因此它不得包含任何定义,而只能包含声明.如果文件同时包含定义和声明,则两个输出文件将产生重复的符号,并且链接器将失败.为避免这种情况,必须将定义放在其他文件或C源文件的前言中.

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.

这篇关于使用cgo时的多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆