Anton
Anton

Reputation: 1966

How to use C++ shared library in Go code with the help of SWIG?

I have a 3rd party C++ .so library that I want to use in my Go code. I can make it work with plain C/C++, but fail to connect to Go.

The library has a big header file and the function I need is declared in it like so (renamed for a simpler look):

typedef unsigned long (*INTERFACE_EXAMPLE_FUNC)(int example_var);
#ifdef PC_STATIC_LIBS
extern "C" unsigned long Example_func(int example_var);
#endif //PC_STATIC_LIBS

(I assume it's easier to link a static lib, so I put #define PC_STATIC_LIBS on top of the header)

I've spent many hours trying to link this library without SWIG, but cgo wouldn't parse the C++ header, giving me tons of error messages. So, I'm trying to use SWIG now. Currently my swig interface file example.i looks as follows:

%module example
 %{
 #include "libheader.h"
 extern unsigned long Example_func(int example_var);
 %}
 extern unsigned long Example_func(int example_var);

Steps I take:

  1. run swig command: swig -go -cgo -c++ -intgosize 64 -use-shlib -soname examplelib.so example.i
  2. go install

Results I get:

/usr/bin/ld: $WORK/b001/_x003.o: in function `_wrap_Example_func_examplelib_8c0447b5964daffe':
./examplelib_wrap.cxx:302: undefined reference to `Example_func'
collect2: error: ld returned 1 exit status

All the files that are being used are in the same directory. I also have a copy of the library placed in my /usr/local/lib and ldconfig -p shows it.

What am I doing wrong here?

Upvotes: 2

Views: 4798

Answers (1)

Anton
Anton

Reputation: 1966

I managed to finally link the C++ shared library to my Go code by adding extra cgo compilation tags to the .go file produced by SWIG. This wasn't obvious thing to do as I thought SWIG didn't need any further adjustments after it was run.

So the two lines of code that fix the issue are:

#cgo CFLAGS: -std=c99
#cgo LDFLAGS: -L. -l:examplelib.so

LDFLAGS says to look for the library 'examplelib.so' in the current path.

Upvotes: 3

Related Questions