go - CGo不在同一目录中编译C文件

标签 go cgo

我正在尝试在同一目录中使用单独的 C 源文件创建 CGO 程序。正如官方 Cgo 文档中所述,Cgo 将编译同一目录中的所有 C 文件,但在这种情况下,它不会编译 C 文件。然后给出链接器错误。

我的测试.go

package main

/*

#include <stdlib.h>
#include "myTest.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)
}

我的测试.h

void print_str(char *s);

我的测试.c

#include "stdio.h"

void print_str(char *s)
{
    printf("%s\n", s?s:"nil");
}

编译时出现以下错误:

> go build myTest.go

# command-line-arguments
/tmp/go-build989557946/b001/_x002.o: In function `_cgo_4c80c9e4eaf0_Cfunc_print_str':
/tmp/go-build/cgo-gcc-prolog:49: undefined reference to `print_str'
collect2: error: ld returned 1 exit status

Go 版本是:

> go version
go version go1.10 linux/amd64

最佳答案

$ go help build
usage: go build [-o output] [-i] [build flags] [packages]

Build compiles the packages named by the import paths,
along with their dependencies, but it does not install the results.

If the arguments to build are a list of .go files, build treats
them as a list of source files specifying a single package.

<< SNIP>>

If the arguments to build are a list of .go files, build treats them as a list of source files specifying a single package.

> go build myTest.go

构建文件 myTest.go

运行

> go build

关于go - CGo不在同一目录中编译C文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49556169/

相关文章:

azure - 如何使用 Go SDK 列出 Azure 存储中的共享

mongodb - 使用 gin-golang 将数据从 mongodb 显示到 html 页面?

go - go build/run 执行时出错

google-app-engine - 从 App Engine(第二代 CloudSQL)GO 连接到 CloudSQL

go - #cgo LDFLAGS中的无效标志

cgo 使用 c struct 数组并在 go 中赋值

go - 执行不接受参数的方法

c++ - cgo : iostream:38:28: fatal error: bits/c++config. h 编译错误:没有那个文件或目录

go - CGO 指针检查中的已知实现错误

cgo - 如何将字符串转换为 C 固定字符数组