【问题标题】:CGo not compiling C files in same directoryCGo不在同一目录中编译C文件
【发布时间】:2018-03-29 22:59:46
【问题描述】:

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

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

myTest.h

void print_str(char *s);

myTest.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 build,所以它只会构建一个文件。您应该构建“包”,请参阅How to Write Go Code
  • 您是如何解决问题的?我也有同样的问题...
  • 回答我自己:根据golang.org/doc/code.html,重要的部分是如果应该执行.go 文件,则使用“main”作为包名(=包含“main”函数)。那是我的错!

标签: go cgo


【解决方案1】:
$ 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>>

如果要构建的参数是 .go 文件的列表,则 build 会处理它们 作为指定单个包的源文件列表。

> go build myTest.go

构建文件myTest.go

运行

> go build

【讨论】:

  • 在我的例子中,这个包被称为“main”。我必须创建一个名为“main”的文件夹并将所有文件放在那里,这样我就可以“go build -o myExecutable main”。感谢您的回答。
  • 更正上一条评论。命令是“go build -o myExecutable ./main”
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2019-11-07
相关资源
最近更新 更多