在我的項目中,我使用回調進行從 C 到 go 的雙向調用,反之亦然,使用 CGO。我通過將 C 部分編譯到庫中,然后將 go 部分編譯到庫中,然后最后的鏈接器傳遞將它們放在一起,解決了循環依賴的問題。這在不使用 go 模塊時工作正常。Go 源文件明確列在命令行上。有人告訴我,從 go 1.12 開始“這不是正確的方法”。隨著項目的發展,我現在想使用 go 模塊。不幸的是,這改變了 go 編譯器的行為。它現在想要解決外部依賴關系并將它們隱式包含在輸出文件中。由于循環依賴,它現在總是以未定義的引用或多個定義結束。如何以“正確的方式”使用 cgo 和 go 模塊時解決循環依賴關系?這是說明問題的最小示例。從 Makefile 中的調用中刪除文件名“hello.go”以查看它是如何分崩離析的。這是錯誤消息:hello.c:3: multiple definition of `c_hello'; $WORK/b001/_cgo_hello.o:/tmp/go-build/hello.c:3: first defined here生成文件:libchello.a: Makefile hello.c gcc -fPIC -c -o chello.o hello.c ar r libchello.a chello.olibgohello.a: Makefile hello.go libchello.a env CGO_LDFLAGS=libchello.a go build -buildmode=c-archive -o libgohello.a hello.gomain: Makefile main.c libgohello.a libchello.a gcc -o main main.c libchello.a libgohello.a -pthread.PHONY: cleanclean: rm -f main *.a *.o echo "extern void go_hello();" > libgohello.h你好,去:package main/*extern void c_hello();*/import "C"import "time"import "fmt"//export go_hellofunc go_hello() { fmt.Printf("Hello from go\n") time.Sleep(1 * time.Second) C.c_hello()}func main() {}libgohello.h:extern void go_hello();你好?:#include "libgohello.h"#include <stdio.h>void c_hello() { printf("Hello from c\n"); go_hello();}主.c:void c_hello();int main() { c_hello();}去.mod:module hehoe.de/cgocircular
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消