0

I am using this:

// foo.h
#ifdef __cplusplus
extern "C" {
#endif
  void foo();
#ifdef __cplusplus
}
#endif

//foo.cc
void foo() {
  cout << "Hello World" << endl;
}

to link between my cgo process and c++ process. I want to access a golang function from my c++ function foo. My go looks like:

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

func golangPart() {
  //do stuff in go
}

func main() {
  C.foo()
}

I want to access golangPart() from the c++. I have tried this:

//foo.h

void golangPart();

#ifdef __cplusplus
extern "C" {
#endif
  void foo();
#ifdef __cplusplus
}
#endif

//foo.cc

void foo() {
  golangPart();
}

But it gave me this error:

./foo.cc:42: undefined reference to `golangPart()'

collect2.exe: error: ld returned 1 exit status

Community
  • 1
  • 1
Ank i zle
  • 2,089
  • 3
  • 14
  • 36
  • 1
    You must mark any Go function that you want callable from C (or C++) code, using the `export` comment. This only works for package `main`; see https://stackoverflow.com/q/58433624/1256452. – torek Feb 22 '20 at 01:43
  • I would also place the declaration of `golangPart` under the `extern "C"` scope as it should obviously use C linkage as well. – kostix Feb 22 '20 at 12:49

0 Answers0