C++ Bindings, CGO

(Johann Forster) #1

I am trying to compile simple c++ code with golang but there are a few errors:

// namespace test
// {
//     int val = 500;
// }
import "C"

Output: error: unknown type name ‘namespace’
This is most likely because the the compiler is for C and not C++; how can I change this?

// #include <algorithm>
import "C"

Output: fatal error: algorithm: No such file or directory
The include file exists and is found by g++; but the go compiler does not find the file. What do I need to change here? I do not want to include every folder manually.
It’s a C++ header file at /usr/include/c++/8/algorithm; are these headers not included because it’s C and not C++?

I have seen the howto-go-with-cpp but this workaround is not good for the build stack and the deps that I use because it requires to modify the included header files.

Go verions: go1.11.6 linux/arm on a RPi.

(Eric Lindblad) #2

cf: your hyperlink

The README.md file mentions an SO post the latter of which contains the below text hyperlinked to another GitHub repo.

Link to GitHub repo with the full example.

(Johann Forster) #3

The other example uses the same technique as the link that I postet: They create an extra C header and compile the C++ files as libraries which i tried to avoid.

(Eric Lindblad) #4

J. Arrieta’s 2nd example on Linux.

I’m only printing this as I modified the goroutines/Makefile for -std=c++14 and the fact that $LD_LIBRARY_PATH was needed.

eric@darkstar:~$ uname -mp
i686 Intel(R) Atom(TM) CPU N270   @ 1.60GHz
eric@darkstar:~$ go version
go version go1.13.3 linux/386
eric@darkstar:~$ ls /var/log/packages | grep llvm
eric@darkstar:~$ mkdir -p ~/go/src
eric@darkstar:~$ tree ~/go
`-- src

1 directory, 0 files
eric@darkstar:~$ cd ~/go/src
eric@darkstar:~/go/src$ git clone https://github.com/arrieta/golang-cpp-basic-example.git
Cloning into 'golang-cpp-basic-example'...
remote: Enumerating objects: 35, done.
remote: Total 35 (delta 0), reused 0 (delta 0), pack-reused 35
Unpacking objects: 100% (35/35), done.
eric@darkstar:~/go/src$ cd golang-cpp-basic-example/goroutines
eric@darkstar:~/go/src/golang-cpp-basic-example/goroutines$ sed -i 's/7/4/g' Makefile
eric@darkstar:~/go/src/golang-cpp-basic-example/goroutines$ make fancy
clang++ -o libfancy.so fancy.cpp \
-std=c++14 -O3 -Wall -Wextra -fPIC -shared
go build fancy.go
eric@darkstar:~/go/src/golang-cpp-basic-example/goroutines$ echo $LD_LIBRARY_PATH

eric@darkstar:~/go/src/golang-cpp-basic-example/goroutines$ export LD_LIBRARY_PATH=~go/src/golang-cpp-basic-example/goroutines
eric@darkstar:~/go/src/golang-cpp-basic-example/goroutines$ ./fancy


[go] done (elapsed: 1427.264774978 seconds)
eric@darkstar:~/go/src/golang-cpp-basic-example/goroutines$ exit