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:
In this answer, we implement a C++ class and write a C wrapper function to perform the sum of two numbers.
We perform the following steps:
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
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);
}
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
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
}
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)
}
Run the go build
executable file that will be generated. Run executable file ./<execute_name>
.
Let’s run the above code in the playground below:
package main// #include "wrap_sum.hxx"import "C"import "fmt"func main() {a := 5b := 10sum := C.sum_from_cplus(C.int(a), C.int(b))fmt.Printf("Go has result, sum is: %v\n", sum)}
We can expect the following output:
C++ says: Hello to Go!!!!
Go has result, sum is: 15
Free Resources