Can I use c++ in cgo?

Chris_F picture Chris_F · Jul 10, 2012 · Viewed 7.7k times · Source

Is it possible to mix in some C++ code in cgo?

I tried this:

package main
/* 
    #include <iostream>

    extern "C" void test(const char* str)
    {
        std::cout << str;
    }
*/
// #cgo CFLAGS: -x c++
// #cgo LDFLAGS: -lstdc++
import "C"

func main() {
    C.test(C.CString("Testing!!!"))
}

But I get these errors:

error: 'char* CString(_GoString_)' cannot appear in a constant-exp
error: 'void test(const char*)' cannot appear in a constant-expres
error: invalid conversion from 'char* (*)(_GoString_)' to 'long long int' [-fpermissive]
error: invalid conversion from 'void (*)(const char*)' to 'long long int' [-fpermissive]

I'm using go1.0.2 and MinGW-w64 4.7.1

Answer

Darshan Rivka Whittle picture Darshan Rivka Whittle · Jul 10, 2012

@ephemient provided a link to the feature request for this in the Go bug tracker. That in turn provided a link back to How to use C++ in Go? here on Stack Overflow. There's a good discussion there, but the takeaways for me were:

  1. The link to the Go FAQ (Do Go programs link with C/C++ programs?):

    ... The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.

  2. The link to The SWIG documentation for Go.