dongshuogai2343 2019-07-12 09:59
浏览 417
已采纳

Cgo找不到<iostream>之类的标准库

I'm trying to include C++ code in my Go code, but isn't recognized.

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++.

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.

This is the c++ files

test.cpp

#include "test.hpp"
    int test() 
    {
        std::cout << "Hello, World! ";
        return 0;
    }

test.hpp 
#include <iostream>
int test() ;

And this is my go file

//#cgo CXXFLAGS: -I/usr/lib/
//#cgo LDFLAGS: -L/usr/lib/ -lstdc++
//#include "test.hpp"
import "C"

func main() {
    C.test()
}

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.

It's supposed to compile correctly, but instead I have iostream: No such file or directory.

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

  • 写回答

2条回答 默认 最新

  • dongzhong5833 2019-07-12 13:31
    关注

    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).

    This will compile:

    .
    ├── 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()
    }
    

    Put the files in the same folder, run go build

    Hello, World!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决