我有一个奇怪的问题。使用cgo时,将cgo_print.h和cgo_print.c与go文件放在同一目录中就可以了。但是当我将两个文件移动到另一个目录(例如ppp)(将include更改为“ ppp / cgo_print.h”)时,发生了错误,它说
体系结构x86_64的未定义符号: “ _Greet”,引用自: _x002.o中的__cgo_1f58160d7360_Cfunc_Greet (也许您是说:__cgo_1f58160d7360_Cfunc_Greet) ld:找不到架构x86_64的符号
转到文件
package cgo
//#cgo CFLAGS: -I.
//#include <stdlib.h>
//#include "cgo_print.h"
import "C"
import (
"fmt"
"unsafe"
)
func CPrints(msg string) {
name := C.CString("Gopher")
defer C.free(unsafe.Pointer(name))
year := C.int(2018)
ptr := C.malloc(C.sizeof_char * 1024)
defer C.free(unsafe.Pointer(ptr))
size := C.Greet(name, year, (*C.char)(ptr))
b := C.GoBytes(ptr, size)
fmt.Println(string(b))
}
cgo_print.h
#include <stdio.h>
int Greet(const char *name, int year, char *out);
cgo_print.c
#include "cgo_print.h"
int Greet(const char *name, int year, char *out) {
int n;
n = sprintf(out, "Greetings, %s from %d! We come in peace :)", name, year);
return n;
}