How to use C++ in Go

Viewed 143642

In the new Go language, how do I call C++ code? In other words, how can I wrap my C++ classes and use them in Go?

12 Answers

Seems that currently SWIG is best solution for this:

https://www.swig.org/Doc4.0/Go.html

It supports inheritance and even allows to subclass C++ class with Go struct so when overridden methods are called in C++ code, Go code is fired.

Section about C++ in Go FAQ is updated and now mentions SWIG and no longer says "because Go is garbage-collected it will be unwise to do so, at least naively".

This can be achieved using command cgo.

In essence 'If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package. For example:'
source:https://golang.org/cmd/cgo/

// #include <stdio.h>
// #include <errno.h>
import "C"
Related