Golang中gccgo无法编译cgo的问题

Golang中gccgo无法编译cgo的问题 我正在尝试使用gccgo编译一个简单的Go程序。我的代码使用了cgo,但gccgo无法编译它。以下是我的代码(使用Go编译器可以正常编译):

package main

// #include <stdio.h>
// #include <stdlib.h>
//
// static void myprint(char* s) {
//   printf("%s\n", s);
// }
import "C"
import "fmt"
func main(){
    fmt.Println("Start")
    cs := C.CString("Print from C")
    C.myprint(cs)
    fmt.Println("End")
}

当我使用 gccgo main.go -o gccoutput 编译代码时,出现以下错误:

main.go:9:9: error: import file ‘C’ not found import “C” ^ main.go:13:8: error: reference to undefined name ‘C’ cs := C.CString(“Print from C”) ^ main.go:14:2: error: reference to undefined name ‘C’ C.myprint(cs) ^

有什么办法可以解决这个问题吗?


更多关于Golang中gccgo无法编译cgo的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

你能解释一下 -compiler 是什么意思吗? 我尝试执行:

go build -compiler=powerpc-linux-gnu-gccgo main.go

结果得到了:

标志 -compiler 的值 “powerpc-linux-gnu-gccgo” 无效:未知的编译器 “powerpc-linux-gnu-gccgo” 用法:go build [-o 输出] [-i] [构建标志] [包] 运行 ‘go help build’ 查看详情。

更多关于Golang中gccgo无法编译cgo的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


$ cat tom.go
package main

// #include <stdio.h>
// #include <stdlib.h>
//
// static void myprint(char* s) {
//   printf("%s\n", s);
// }
import "C"
import "fmt"

func main() {
	fmt.Println("Start")
	cs := C.CString("Print from C")
	C.myprint(cs)
	fmt.Println("End")
}

go:

$ go version
go version devel +758ac371ab Tue Aug 25 21:15:43 2020 +0000 linux/amd64

$ go run tom.go
Start
Print from C
End

gccgo:

$ gccgo --version
gccgo (Ubuntu 10-20200411-0ubuntu1) 10.0.1 20200411 (experimental) [master revision bb87d5cc77d:75961caccb7:f883c46b4877f637e0fa5025b4d6b5c9040ec566]

$ go run -compiler=gccgo tom.go
Start
Print from C
End
$

gccgo不支持cgo。cgo是Go官方工具链(gc)的特性,它通过调用外部C编译器来处理C代码。gccgo是GCC的Go前端,其设计目标不同,没有实现cgo机制。

如果你需要在gccgo中使用C代码,可以考虑以下两种替代方案:

  1. 使用SWIG(Simplified Wrapper and Interface Generator):通过SWIG生成Go和C之间的绑定代码。

  2. 直接使用gccgo的C互操作特性:gccgo支持通过//extern注释直接调用C函数,但语法与cgo不同。

以下是使用gccgo直接调用C函数的示例:

package main

// #cgo CFLAGS: -I.
// #cgo LDFLAGS: -L. -lmylib
// #include "mylib.h"
import "C"

// 改为使用gccgo的extern特性
/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lmylib
#include "mylib.h"
*/
import "C"

// 或者完全分离C代码,通过C共享库调用

更实际的方案是创建一个独立的C库,然后通过gccgo调用:

mylib.c:

#include <stdio.h>
#include "mylib.h"

void myprint(char* s) {
    printf("%s\n", s);
}

mylib.h:

#ifndef MYLIB_H
#define MYLIB_H

void myprint(char* s);

#endif

main.go:

package main

// #cgo CFLAGS: -I.
// #cgo LDFLAGS: -L. -lmylib
// #include "mylib.h"
import "C"
import "fmt"

func main() {
    fmt.Println("Start")
    cs := C.CString("Print from C")
    C.myprint(cs)
    fmt.Println("End")
}

编译步骤:

# 编译C库
gcc -c -fPIC mylib.c -o mylib.o
gcc -shared mylib.o -o libmylib.so

# 使用Go官方工具链编译(支持cgo)
go build -o output main.go

# 或者如果你坚持使用gccgo,需要完全避免cgo语法

对于必须使用gccgo且需要C互操作的情况,建议将C功能封装到独立的共享库中,然后通过系统调用或FFI方式调用。

回到顶部