Cgo找不到< iostream>之类的标准库. [英] Cgo can't find standard libraries like <iostream>
问题描述
我正在尝试在Go代码中包含C ++代码,但无法识别.
I'm trying to include C++ code in my Go code, but isn't recognized.
我首先想到它将其视为C代码并尝试(并失败)这样的编译方式,但实际上删除包含行可为我提供c ++错误疑难解答,例如错误:"cout"不是"std"的成员
该代码可以使用g ++正确编译.
I first thought that it considers it as C code and try (and fail) to compile as such, but removing the include line actually gives me c++ error troubleshooting like this
error: ‘cout’ is not a member of ‘std’
The code compiles correctly with g++.
我尝试添加-lstdc ++ LDLFLAG,并在CXXFLAG中添加到lib的路径,但这并没有改变.
I have tried to add the -lstdc++ LDLFLAG, and add the path to the lib in CXXFLAG but it doesn't change a thing.
我做了其他一些测试(都失败了),但这是最小的测试.
I have made some other tests (and all fail) but this is the smallest one.
这是c ++文件
test.cpp
#include "test.hpp"
int test()
{
std::cout << "Hello, World! ";
return 0;
}
test.hpp
#include <iostream>
int test() ;
这是我的go文件
//#cgo CXXFLAGS: -I/usr/lib/
//#cgo LDFLAGS: -L/usr/lib/ -lstdc++
//#include "test.hpp"
import "C"
func main() {
C.test()
}
我使用 go build
进行编译,但我也尝试使用 env CGO_ENABLED CGO_CXXFLAGS =-std = c ++ 11" go build
(env部分是fish具体),并返回相同的错误.
I compile using go build
but I have also tried to use env CGO_ENABLED CGO_CXXFLAGS="-std=c++11" go build
(the env part is fish specific) and it returns the same error.
应该正确编译,但是我有 iostream:没有这样的文件或目录
.
It's supposed to compile correctly, but instead I have iostream: No such file or directory
.
我尝试按照注释中的建议添加 CFLAGS:-x c ++
,编译器在正确的位置进行搜索,但又出现了另一个错误,从'void *'到'_cgo_96e70225d9dd_Cfunc_test(void*)::< unnamed struct> *'[-fpermissive] ,我不知道它是否与此新的flafg相关
EDIT :
I tried to add CFLAGS: -x c++
as suggested in the comments, the compiler searches at the right place, but I get another error invalid conversion from ‘void*’ to ‘_cgo_96e70225d9dd_Cfunc_test(void*)::<unnamed struct>*’ [-fpermissive]
and I don't know if it's related to this new flafg
推荐答案
cgo使得用Go封装C非常容易,但是C ++有点不同.您必须外部"C"
您要在C ++中使函数名称具有'C'的函数'链接,否则链接器将看不到该功能.因此,实际的问题出在C ++头文件中.如果因为它是一个库而无法更改C ++代码,则可能必须编写包装器(
cgo makes it very easy to wrap C with Go, but C++ is a bit different. You have to extern "C"
the functions that you want to make a function-name in C++ have 'C' linkage, otherwise the linker won't see the function. So, the actual problem is in the C++ header file. If you can't change the C++ code because it's a library, you may have to write wrappers (example).
这将编译:
.
├── test.cpp
├── test.go
└── test.hpp
test.hpp
#ifdef __cplusplus
extern "C" {
#endif
int test();
#ifdef __cplusplus
}
#endif
test.cpp
#include <iostream>
#include "test.hpp"
int test() {
std::cout << "Hello, World! ";
return 0;
}
test.go
package main
// #cgo CXXFLAGS: -I/usr/lib/
// #cgo LDFLAGS: -L/usr/lib/ -lstdc++
// #include "test.hpp"
import "C"
func main() {
C.test()
}
将文件放在同一文件夹中,运行 go build
Put the files in the same folder,
run go build
你好,世界!
这篇关于Cgo找不到< iostream>之类的标准库.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!