CGo没有在同一目录中编译C文件

时间:2018-03-29 12:31:24

标签: go cgo

我正在尝试使用单独的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 version is:

> go version
go version go1.10 linux/amd64

1 个答案:

答案 0 :(得分:4)

$ 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