繁体   English   中英

无法运行简单的 go 程序包含 cgo 东西

[英]Can't run simple go program contains cgo stuff

我正在尝试运行以下简单的 go 代码,参考简单的 C 代码(所有文件都位于同一文件夹中):

主要.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代码:

库文件h

void print_str(char *s);

图书馆.c

#include "stdio.h"
 
void print_str(char *s)
{
    printf("%s\n", s?s:"nil");
}

尝试在 Windows 和 Linux 中运行go build main.go ,最新版本为 go (1.16.5) 并得到:

# 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

我在这里错过了什么?

首先我编译了共享库gcc -fPIC -shared lib.c -o lib.so

然后我在你的 go 文件中添加了对 that.so 的引用#cgo LDFLAGS: -L${SRCDIR} lib.so (Ref: https://golang.org/cmd/cgo/ )

$ go run main.go
hi how are you

最终代码:

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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM