首页 > 解决方案 > golang 使用 gcc 而不是 g++ 构建

问题描述

我正在尝试构建在 Linux 上调用 c++ 创建的.so (a.so)文件的 Go,但我发现该go build .命令始终使用 gcc 而不是g++ 构建。我已经把它.cpp放在根目录而不是子目录中。

这是go build命令的输出

client.go:90:10: could not determine kind of name for C.Init
cgo:
gcc errors for preamble:
In file included from client.go:8:
a.h:34:1: error: unknown type name 'class'
   34 | class A {
      | ^~~~~
a.h:34:11: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
   34 | class A {
      |           ^               ^

这是client.go调用 C 代码:

package main

// #cgo windows LDFLAGS: -la
// #cgo windows CXXFLAGS: -DWINDOWS
// #cgo linux LDFLAGS: -liba
// #cgo LDFLAGS: -L./libs
// #cgo CXXFLAGS: -I./
// #include "a.h"
import "C"

func function() {
    handle, _ := dlOpen(PATH_TO_SO_FILE)
    blob := C.Init(handle)
}

这是 dlOpen 相关代码,用 Go 编写:

// +build linux

package main

// #cgo linux LDFLAGS: -ldl
// #include <dlfcn.h>
// #include <stdlib.h>
import "C"

import "errors"
import "unsafe"

type Handle {
    c unsafe.Pointer
}

func dlOpen(filename string) (Handle, error) {
    ptr := C.CString(filename)
    defer C.free(unsafe.Pointer(ptr))
    ret := C.dlopen(ptr, C.RTLD_LAZY)
    if ret != nil {
        return Handle{ret}, nil
    }
    return Handle{ret}, errors.New(C.GoString(C.dlerror()))
}

这里是a.h

class A {
    public:
        Init(MHANDLE handle);
}

标签: gocgo

解决方案


您的问题不在于 cpp 文件。
你在 go 文件中写了// #include "a.h"
Go 目前将其编译为 c 并且不支持 c++,而且看起来它永远不会支持。
您唯一的选择是使头文件在 c 中有效。


推荐阅读