0

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)
  • Does this answer your question? [How to use C++ in Go](https://stackoverflow.com/questions/1713214/how-to-use-c-in-go) – Öö Tiib Aug 09 '23 at 10:47
  • I have read that but no it does not, I still can not understand how can I successfully link a cpp library – Omar Khalil Aug 09 '23 at 10:51
  • Then you have to improve your question with information in what step and with what errors you are stuck (that means your scripts, code and errors you get verbatim in question). – Öö Tiib Aug 09 '23 at 11:01
  • Please provide enough code so others can better understand or reproduce the problem. – Community Aug 09 '23 at 11:18
  • @ÖöTiib is it clearer now? – Omar Khalil Aug 09 '23 at 11:26
  • I see you nowhere trying to use neither C wrapper nor SWIG, your Adder is fully C++ function and C++ functions are name-mangled for linker so reference to it is not found as expected. – Öö Tiib Aug 09 '23 at 11:33
  • I have already removed the C wrapper, because I got that same error, so how can I proper link Adder function? – Omar Khalil Aug 09 '23 at 11:37

0 Answers0