例如,我有两个具有相同函数名的C库:
hello1.c:
#include <stdio.h>
void hello() {
printf("Hello from C hello1.c\n");
}
hello2.c:
#include <stdio.h>
void hello() {
printf("Hello from C hello2.c\n");
}
如何将其链接到Go可执行二进制文件?静态或动态无关紧要。
我已经尝试过甚至将其静态链接到单独的Go插件中,但是它不起作用–只有来自两个Go插件的调用hello
函数来自hello1.c
:
hello1.go Go插件:
package main
/*
#cgo LDFLAGS: -L${SRCDIR}/lib -lhello1
void hello();
*/
import "C"
import "fmt"
func Hello() {
fmt.Println("Hello from Go plugin hello1.go")
fmt.Println("Call C hello1.c")
C.hello()
}
hello2.go Go插件:
package main
/*
#cgo LDFLAGS: -L${SRCDIR}/lib -lhello2
void hello();
*/
import "C"
import "fmt"
func Hello() {
fmt.Println("Hello from Go plugin hello2.go")
fmt.Println("Call C hello2.c")
C.hello()
}
main.go可执行二进制文件:
package main
import (
"fmt"
"plugin"
)
func main() {
p1, err := plugin.Open("hello1/hello1.so")
if err != nil {
panic(err)
}
fmt.Println("Load Go plugin hello1.so")
p2, err := plugin.Open("hello2/hello2.so")
if err != nil {
panic(err)
}
fmt.Println("Load Go plugin hello2.so")
h1, err := p1.Lookup("Hello")
if err != nil {
panic(err)
}
h2, err := p2.Lookup("Hello")
if err != nil {
panic(err)
}
fmt.Println("Call Go plugin hello1.go")
h1.(func())()
fmt.Println("\nCall Go plugin hello2.go")
h2.(func())()
}
运行main
可执行二进制文件后的输出:
./main
Load Go plugin hello1.so
Load Go plugin hello2.so
Call Go plugin hello1.go
Hello from Go plugin hello1.go
Call C hello1.c
Hello from C hello1.c
Call Go plugin hello2.go
Hello from Go plugin hello2.go
Call C hello2.c
Hello from C hello1.c <=== here hello1.c, but I expected hello2.c
更新:
我已经完成了golang的问题以获得答案:https : //github.com/golang/go/issues/42854
我在github问题https://github.com/golang/go/issues/42854中得到了我的问题的答案
When I compile C libraries I should use -fvisibility=hidden
gcc flag.