I want to use some c++ libraries in Golang, so I used CMake to create and test my c++ library. However, when I try to use cgo to link and use the library I keep getting undefined references error.
I tried to use SWIG but I could not figure out how to use it properly, and also tried using a C wrapper and it worked fine with C programs, but when using cgo, I kept getting the same error with the c++ functions it invokes.
I am using CMake 3.27, Ubuntu 20.04, and Go 1.20.7
My Golang code:
package main
//#cgo CPPFLAGS: -I /home/omar/CMake_Projects/PROJECT_HEADER
//#cgo LDFLAGS: -L /home/omar/CMake_Projects/PROJECT_HEADER/build -l MyLibrary
//#include "cpp.h"
import (
"C"
)
import "fmt"
func main() {
a := C.int(9878)
b := C.int(4)
c := C.Adder(a, b)
fmt.Println(c)
}
My cpp.h:
#ifndef connect
#define connect
int Adder(int a, int b);
#endif
My add.cpp:
#include "ConnectionHeader.h"
#include <iostream>
using namespace std;
int Adder(int a, int b) {
cout << a + b << " ";
return a+b;
}
Error Message:
/usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
/usr/bin/ld: /tmp/go-link-3832133047/000001.o: in function `_cgo_7a5a50d50ed6_Cfunc_Adder':
/tmp/go-build/cgo-gcc-prolog:54: undefined reference to `Adder'
collect2: error: ld returned 1 exit status (exit status 1)