Golang中导入C时出错:cc1.exe报错"参数过多"

Golang中导入C时出错:cc1.exe报错"参数过多" 这是我的代码:

package main

import (
    "C"
    "fmt"
    "unsafe"
)

func main() {
    c := 1
    var Cvar C.int = 1
    cup := unsafe.Pointer(&c)
    cbyte := C.GoBytes(cup, Cvar)
    fmt.Printf("%x", cbyte)
}

我尝试导入并使用C包,但在编译时一直遇到这个错误:

# runtime/cgo
cc1.exe: error: too many filenames given.  Type cc1.exe --help for usage
cc1.exe: fatal error: Files/Win-builds/include: No such file or directory
compilation terminated.
exit status 2
Process exiting with code: 1

在64位Windows系统上,我的Go版本和GCC版本如下:

gcc --version gcc (GCC) 4.8.3 Copyright © 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

go version go version go1.14 windows/amd64

我遗漏了什么导致它抛出这个错误?


更多关于Golang中导入C时出错:cc1.exe报错"参数过多"的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中导入C时出错:cc1.exe报错"参数过多"的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这个错误通常是由于Windows路径中包含空格导致的。cc1.exe是GCC的编译器组件,当遇到包含空格的路径(如Program Files)时,会错误地将单个路径解析为多个参数。

在你的错误信息中可以看到:

Files/Win-builds/include: No such file or directory

这明显是Program Files路径被截断了。

解决方案是确保GCC安装在没有空格的路径中。以下是具体步骤:

1. 重新安装GCC到无空格路径: 卸载当前GCC,重新安装到类似以下路径:

  • C:\mingw64\
  • C:\gcc\
  • C:\TDM-GCC\

2. 更新环境变量: 安装后,确保系统环境变量PATH包含GCC的bin目录,例如:

C:\mingw64\bin

3. 验证安装: 重新打开命令行验证:

gcc --version
where gcc

4. 如果必须使用当前路径,可以尝试符号链接: 以管理员身份运行CMD:

mklink /J C:\Win-builds "C:\Program Files\Win-builds"

然后设置环境变量指向C:\Win-builds

示例代码调整: 你的Go代码本身是正确的,但需要确保CGO能正确找到GCC。这里是一个更完整的示例:

package main

// #include <stdlib.h>
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    // 创建Go整数
    goInt := 42
    
    // 转换为C.int
    cInt := C.int(goInt)
    
    // 获取指针并转换为C指针
    ptr := unsafe.Pointer(&goInt)
    
    // 使用C.malloc分配内存(替代C.GoBytes)
    size := C.sizeof_int
    cptr := C.malloc(size)
    defer C.free(cptr)
    
    // 复制内存
    C.memcpy(cptr, ptr, size)
    
    // 转换回Go字节切片
    bytes := C.GoBytes(cptr, C.int(size))
    fmt.Printf("原始值: %d, 字节表示: %x\n", goInt, bytes)
}

编译前确保设置正确的环境变量:

set CGO_ENABLED=1
set CC=gcc
set CXX=g++

如果问题仍然存在,检查是否有其他GCC版本冲突:

where gcc
where cc1

这个错误与Go代码无关,纯粹是Windows路径空格导致的GCC调用问题。

回到顶部