英文:
Can't run simple go program contains cgo stuff
问题
我正在尝试运行以下简单的Go代码,参考了简单的C代码(所有文件都位于同一个文件夹中):
main.go
package main
/*
#include <stdlib.h>
#include "lib.h"
*/
import "C"
import "unsafe"
func Print(s string) {
cs := C.CString(s)
C.print_str(cs)
C.free(unsafe.Pointer(cs))
}
func main() {
str1 := "hi how are you\n"
Print(str1)
}
C代码:
lib.h
void print_str(char *s);
lib.c
#include "stdio.h"
void print_str(char *s)
{
printf("%s\n", s?s:"nil");
}
尝试在Windows和Linux上使用最新版本的Go(1.16.5)运行go build main.go
,结果如下:
# command-line-arguments
/tmp/go-build3048423534/b001/_x002.o: In function `_cgo_976ac389362d_Cfunc_print_str':
/tmp/go-build/cgo-gcc-prolog:61: undefined reference to `print_str'
collect2: error: ld returned 1 exit status
我在这里漏掉了什么?
英文:
I'm trying to run the following simple go code with reference to simple C code (all files located in the same folder):
main.go
package main
/*
#include <stdlib.h>
#include "lib.h"
*/
import "C"
import "unsafe"
func Print(s string) {
cs := C.CString(s)
C.print_str(cs)
C.free(unsafe.Pointer(cs))
}
func main() {
str1 := "hi how are you\n"
Print(str1)
}
The C code:
lib.h
void print_str(char *s);
lib.c
#include "stdio.h"
void print_str(char *s)
{
printf("%s\n", s?s:"nil");
}
Tried to run go build main.go
, both in Windows and Linux, with the latest version of go (1.16.5) and got:
# command-line-arguments
/tmp/go-build3048423534/b001/_x002.o: In function `_cgo_976ac389362d_Cfunc_print_str':
/tmp/go-build/cgo-gcc-prolog:61: undefined reference to `print_str'
collect2: error: ld returned 1 exit status
What am I missing here?
答案1
得分: 3
首先,我编译了共享库:
gcc -fPIC -shared lib.c -o lib.so
然后,在你的Go文件中添加了对该.so文件的引用:
#cgo LDFLAGS: -L${SRCDIR} lib.so
参考链接:https://golang.org/cmd/cgo/
最终代码:
package main
/*
#include <stdlib.h>
#include <lib.h>
#cgo LDFLAGS: -L${SRCDIR} lib.so
*/
import "C"
import "unsafe"
func Print(s string) {
cs := C.CString(s)
C.print_str(cs)
C.free(unsafe.Pointer(cs))
}
func main() {
str1 := "hi how are you\n"
Print(str1)
}
以上是翻译好的内容。
英文:
First I compiled the shared lib
gcc -fPIC -shared lib.c -o lib.so
Then I added a reference to that .so in your go file
#cgo LDFLAGS: -L${SRCDIR} lib.so
(Ref: https://golang.org/cmd/cgo/)
$ go run main.go
hi how are you
Final code:
package main
/*
#include <stdlib.h>
#include <lib.h>
#cgo LDFLAGS: -L${SRCDIR} lib.so
*/
import "C"
import "unsafe"
func Print(s string) {
cs := C.CString(s)
C.print_str(cs)
C.free(unsafe.Pointer(cs))
}
func main() {
str1 := "hi how are you\n"
Print(str1)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论