我想从 C 函数空间调用 go func,但程序抛出构建错误。
示例.go
package main
/*
#include "test.c"
*/
import "C"
import "fmt"
func Example() {
fmt.Println("this is go")
fmt.Println(C.GoString(C.myprint(C.CString("go!!"))))
}
// export receiveC (remove the extra space between // and export)
func receiveC(msg *C.char) {
fmt.Println(C.GoString(msg))
}
func main() {
Example()
}
Run Code Online (Sandbox Code Playgroud)
测试.c
#include <stdio.h>
extern void receiveC(char *msg);
char* myprint(char *msg) {
receiveC(msg); // calling the exported go function
return msg;
}
Run Code Online (Sandbox Code Playgroud)
当我执行命令来运行/构建(go build
或go run example.go
或go build example.go
)程序时,它会抛出错误:
# github.com/subh007/goodl/cgo
Undefined symbols for architecture x86_64:
"_receiveC", referenced from:
_myprint in example.cgo2.o
__cgo_6037ec60b2ba_Cfunc_myprint in example.cgo2.o
_myprint in test.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)
我正在按照cgo 幻灯片编写程序。如果这里有任何错误,请告诉我。
Edit1:我使用的是 OS-X 10.9 操作系统。
Edit2:我在 之间有一个额外的空格,和// export
之间不应该有空格。但现在我在构建时遇到以下错误://
export
# github.com/subh007/goodl/cgo
duplicate symbol _myprint in:
$WORK/github.com/subh007/goodl/cgo/_obj/_cgo_export.o
$WORK/github.com/subh007/goodl/cgo/_obj/example.cgo2.o
duplicate symbol _receiver_go in:
$WORK/github.com/subh007/goodl/cgo/_obj/_cgo_export.o
$WORK/github.com/subh007/goodl/cgo/_obj/example.cgo2.o
duplicate symbol _myprint in:
$WORK/github.com/subh007/goodl/cgo/_obj/_cgo_export.o
$WORK/github.com/subh007/goodl/cgo/_obj/test.o
duplicate symbol _receiver_go in:
$WORK/github.com/subh007/goodl/cgo/_obj/_cgo_export.o
$WORK/github.com/subh007/goodl/cgo/_obj/test.o
ld: 4 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)
生成重复的符号是因为我已将其test.c
直接包含到 go 文件中。因此这些符号被包含两次。
我认为,编写这段代码的正确方法是(如果我错了,请评论):
定义头文件(test.h):
#ifndef TEST_H_
#define TEST_H_
char* myprint(char *msg);
#endif
Run Code Online (Sandbox Code Playgroud)
定义实现文件(test.c):
#include <stdio.h>
#include "test.h"
extern void receiveC(char *msg);
char* myprint(char *msg) {
receiveC(msg);
return msg;
}
Run Code Online (Sandbox Code Playgroud)
将文件包含到文件 (example.go).h
中:go
package main
/*
#include "test.h"
*/
import "C"
import "fmt"
func Example() {
fmt.Println("this is go")
fmt.Println(C.GoString(C.myprint(C.CString("go!!"))))
}
// make sure that there should be no space between the `//` and `export`
//export receiveC
func receiveC(msg *C.char) {
fmt.Println(C.GoString(msg))
}
func main() {
Example()
}
Run Code Online (Sandbox Code Playgroud)
构建程序:
go build
Run Code Online (Sandbox Code Playgroud)
运行生成的可执行文件(生成的可执行文件具有该cgo
名称,需要进行一些调查才能找到原因)。
$./cgo
Run Code Online (Sandbox Code Playgroud)