我正在尝试使用同一目录中的单独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)
}
Run Code Online (Sandbox Code Playgroud)
myTest.h
void print_str(char *s);
Run Code Online (Sandbox Code Playgroud)
myTest.c
#include "stdio.h"
void print_str(char *s)
{
printf("%s\n", s?s:"nil");
}
Run Code Online (Sandbox Code Playgroud)
编译时,出现以下错误:
> 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
Run Code Online (Sandbox Code Playgroud)
Go版本是:
> go version
go version go1.10 linux/amd64
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)$ 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
Run Code Online (Sandbox Code Playgroud)
建立档案 myTest.go
跑
> go build
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
876 次 |
| 最近记录: |