我正在尝试将一个 go 库转换为由 C 调用,我从一个简单的测试开始(基于一个示例回答我发现有效的另一个问题)文件,但是当我尝试构建时出现错误。我在 C 中有一个结构,我试图将它传递给一个 go 函数,该函数使用该结构中的数据并返回一个值(在这种情况下是一个整数,但最终它将是另一个结构)。
去版本:1.4.2
gccgo 版本:5.0.1
gcc 版本:4.9.2
类型.h
typedef struct num {
int n;
} num;
foo.go
package main
// #include "type.h"
import "C"
func New(x int) C.struct_num {
num := C.struct_num{}
num.n = C.int(x)
return num
}
func Add(num C.struct_num, x int) int {
return int(num.n) + x
}
酒吧.c
#include <stdio.h>
#include "type.h"
extern num go_new(int) __asm__ ("example.main.New");
extern int go_add(num, int) __asm__ ("example.main.Add");
int main() {
num n = go_new(2);
int x = go_add(n, 3);
printf("Result: %d\n", x);
}
生成文件
all: main
main: foo.o bar.c
gcc foo.o bar.c -o main
foo.o: foo.go
go build -compiler gccgo -gccgoflags '-c -o foo.o -fgo-prefix=example' foo.go
clean:
rm -f main *.o
当我运行 make 我得到错误:
gcc foo.o bar.c -o main
foo.o:(.rodata.__go_td_pN23_example.main._Ctype_int[__go_td_pN23_example.main._Ctype_int]+0x18): undefined reference to `__go_type_hash_identity'
foo.o:(.rodata.__go_td_pN23_example.main._Ctype_int[__go_td_pN23_example.main._Ctype_int]+0x20): undefined reference to `__go_type_equal_identity'
foo.o:(.rodata.__go_tdn_example.main..example_main._Ctype_int+0x18): undefined reference to `__go_type_hash_identity'
foo.o:(.rodata.__go_tdn_example.main..example_main._Ctype_int+0x20): undefined reference to `__go_type_equal_identity'
foo.o:(.rodata.__go_td_pN30_example.main._Ctype_struct_num[__go_td_pN30_example.main._Ctype_struct_num]+0x18): undefined reference to `__go_type_hash_identity'
foo.o:(.rodata.__go_td_pN30_example.main._Ctype_struct_num[__go_td_pN30_example.main._Ctype_struct_num]+0x20): undefined reference to `__go_type_equal_identity'
foo.o:(.rodata.__go_tdn_example.main..example_main._Ctype_struct_num+0x18): undefined reference to `__go_type_hash_identity'
foo.o:(.rodata.__go_tdn_example.main..example_main._Ctype_struct_num+0x20): undefined reference to `__go_type_equal_identity'
foo.o:(.rodata.__go_td_pN24_example.main._Ctype_void[__go_td_pN24_example.main._Ctype_void]+0x18): undefined reference to `__go_type_hash_identity'
foo.o:(.rodata.__go_td_pN24_example.main._Ctype_void[__go_td_pN24_example.main._Ctype_void]+0x20): undefined reference to `__go_type_equal_identity'
foo.o:(.rodata.__go_tdn_example.main..example_main._Ctype_void+0x18): undefined reference to `__go_type_hash_identity'
foo.o:(.rodata.__go_tdn_example.main..example_main._Ctype_void+0x20): undefined reference to `__go_type_equal_identity'
collect2: error: ld returned 1 exit status
Makefile:4: recipe for target 'main' failed
make: *** [main] Error 1
根据我从其他搜索中了解到的情况,这些错误与对 C go 库的调用有关,表明这可能没有被编译到目标文件中。我也尝试过直接在 make 文件中运行 gccgo 并得到相同的结果。任何见解和/或帮助表示赞赏。谢谢。
编辑
多亏了这篇文章,我才知道这一点。显然我需要在 Makefile 中为 main 调用 gccgo,因为 gcc 不知道如何正确链接 go 运行时。