douying9296 2018-03-29 12:31
浏览 339
已采纳

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

I am trying to create a CGO program with separate C source file in the same directory. As mentioned in the official Cgo docs, Cgo will compile all C files in the same directory but in this case, it is not compiling the C file. And later gives a linker error.

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
"
    Print(str1)
}

myTest.h

void print_str(char *s);

myTest.c

#include "stdio.h"

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

While compiling, I am getting the following error:

> 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条回答 默认 最新

  • duanbei1598 2018-03-29 14:54
    关注
    $ 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
    

    builds file myTest.go

    Run

    > go build
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B