How to use C++ in Go with the C_wrapper function

The calling of C++ in Go is not as straight forward as it is in C. It requires more work to run C++ in Go. There are two ways to run C++ in Go:

  • Using the C_wrapper function
  • Using SWIGSWIG is used to generate the c_wrapper function for C++ to call in Go.

In this answer, we implement a C++ class and write a C wrapper function to perform the sum of two numbers.

C++ interface with GO
C++ interface with GO

Steps

We perform the following steps:

  1. Create a header file sum.hxx and paste the code below:

    #ifndef SUM_H
    #define SUM_H
    class SumClass { 
    //create class
    public:
      int Sum(int a, int b); //declare function
    };
    #endif
    
  2. Create a file sum.cxx and paste the code below:

    #include "sum.hxx"
    #include <math.h>
    #include <iostream>
    int SumClass::Sum(int a,int b) {
      std::cout << "C++ says: Sum from Sum funct(" << a << "," << b
        << "), and Sum is:(" << a+b << ")" << std::endl;
      return (a+b);
    }
    
  3. Create a header file wrap_sum.hxx and paste the code below:

    #ifndef WRAP_SUM_H
    #define WRAP_SUM_H
    
    // __cplusplus tells the compiler that inside code is compiled with the c++ compiler
    #ifdef __cplusplus
    // extern "C" tells C++ compiler exports the symbols without a name manging.
    extern "C" {
      #endif
      int sum_from_cplus(int a,int b); //declare wrapper function
      #ifdef __cplusplus
    }
    #endif
    #endif
    
  4. Create a file wrap_sum.cxx and paste the code below.

    #include "wrap_sum.hxx"
    #include "sum.hxx"
    
    int sum_from_cplus(int a, int b) {
      SumClass num; //create object of class SumClass
      return num.Sum(a, b); // Call Sum function using wrapper function sum_from_cplus
    }
    
  5. Create a file main.go and paste the code below:

    package main
    // #include "wrap_sum.hxx"
    import "C"
    import "fmt"
    
    func main() {
    
      a := 5
      b := 10
      sum := C.sum_from_cplus(C.int(a), C.int(b))
      fmt.Printf("Go has result, sum is: %v\n", sum)
    }
    
  6. Run the go build executable file that will be generated. Run executable file ./<execute_name>.

Code

Let’s run the above code in the playground below:

main.go
wrap_sum.hxx
wrap_sum.cxx
sum.cxx
sum.hxx
package main
// #include "wrap_sum.hxx"
import "C"
import "fmt"
func main() {
a := 5
b := 10
sum := C.sum_from_cplus(C.int(a), C.int(b))
fmt.Printf("Go has result, sum is: %v\n", sum)
}

Output

We can expect the following output:

C++ says: Hello to Go!!!! 
Go has result, sum is: 15

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved