Compile C++ with cgo

1,743 views
Skip to first unread message

av

unread,
Apr 11, 2019, 11:54:22 AM4/11/19
to golang-nuts
Hi *,

I want to compile C++ code, because the library I need is C++ only.

Here is my wrapper.hpp:
#include <iostream>

void print() {
  std::cout << "Xx";
}

And here is my main.go:
package main

// #cgo CXXFLAGS: -I.
// #cgo CFLAGS: -I.
// #cgo LDFLAGS:
// #include "wrapper.hpp"
import "C"

func main() {
        C.print()
}

The output of "go build" is:
In file included from ./main.go:6:0:
./wrapper.hpp:1:20: fatal error: iostream: No such file or directory
 #include <iostream>
                    ^
compilation terminated.

I can make this work by using Makefile and static library, but this reduce portability significantly.

Basically I want to create libapt-pkg wrapper, but I don't want to introduce another debian package for the wrapper.

Do you have any idea how to make this work?

Sebastien Binet

unread,
Apr 15, 2019, 4:51:31 AM4/15/19
to av, golang-nuts
you'd need to export a C-only API in the header files you want to use from/with cgo.

ie:

// wrapper.h
#ifdef __cplusplus
extern "C" {
#endif

void print();

#ifdef __cplusplus
}
#endif

and:

// wrapper.cc
#include <iostream>
#include "wrapper.h"

void print() {
    std::cout << "Xx" << std::endl;
}

and, finally:

package main

// #include "wrapper.h"
import "C"

func main() {
    C.print()
}

hth,
-s

ACC ID

unread,
Jul 6, 2022, 4:34:02 PM7/6/22
to golang-nuts
Hello, I tried your example and I got "c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: $WORK\b001\_x002.o: in function `_cgo_d32036b73474_Cfunc_print':
/tmp/go-build/cgo-gcc-prolog:49: undefined reference to `print'
collect2.exe: error: ld returned 1 exit status"
 
Windows 10, VS Code.

Have you some idea why?
Reply all
Reply to author
Forward
0 new messages