Using C++ in Go is a bit tricky. It’s because C++ can’t be used directly in Go. Instead, C++ must be wrapped into C or integrated through another tool, e.g.,
To integrate C++ and Go, we must have SWIG installed. Here’s how it can be done:
For MacBook:
brew install swig
For Linux/Ubuntu:
sudo apt install swig
To understand how to use C++ in Go, we will write a simple code that takes the product of two non-zero numbers. Let’s look at the steps below:
Create a directory named swig
that has one folder multiplier
and a file main.go
in it. We will begin with creating the primary files inside the multiplier
folder.
Create a C++ header file, multiplier.hpp
. Inside it, create a class Multiplier
. The public section of the class will have a constructor Multiplier()
that initializes a private member variable _v
with the value 1. A public method Multiply
will be declared, which takes an integer v
as an argument. This function will be responsible for performing multiplication with the private variable _v
. Another method Get()
will be created to return the final result.
#ifndef _MULTIPLIER_H_#define _MULTIPLIER_H_class Multiplier{public:Multiplier() : _v(1) {} // Initialize _v with 1 for multiplicationvoid Multiply(int v); // New method for multiplicationint Get();private:int _v;};#endif //_MULTIPLIER_H_
Create a C++ file multiplier.cpp
. Inside it, include the previously created header file multiplier.hpp
. Implement the Multiply()
and Get()
method of class Multipler
created in the header file.
#include "multiplier.hpp"void Multiplier::Multiply(int v) {_v *= v;} // Implementation of the Multiply methodint Multiplier::Get() {return _v;}
Create a SWIG file and name it multiplier.swigcxx
. This file will be responsible for wrapping the C++ code so it can be used in Go. We will create a directive that will specify the name of the SWIG module that will be generated. In this code example, we will name it multiplier
. Now, we will include our header file directly in the wrapper file generated by SWIG. For this, we use %{}%
code blocks. At the end of the file, we will include multiplier.hpp
separately to ensure that the C++ class and functions declared in multiplier.hpp
are properly accessible from the Go code.
%module multiplier%{#include "multiplier.hpp"%}%include "multiplier.hpp"
Create a file package.go
.
package multiplierimport "C"
Now we write our main file, i.e., main.go
, inside the swig
directory. In this file, we will pass two numbers we want to multiply to our Multiply()
function. To fulfill the initial constraints of the problem, i.e., both the numbers should be non-zero, we will implement a check using if else
. Get()
will be called to display the final product.
package mainimport ("fmt""tutorial/swig/multiplier")func main() {a := multiplier.NewMultiplier()defer multiplier.DeleteMultiplier(a)num1 := 4 // First number for multiplicationnum2 := 2 // Second number for multiplication// Check if both numbers are non-zeroif num1 != 0 && num2 != 0 {// Multiply the numbersa.Multiply(num1)a.Multiply(num2)fmt.Printf("The product of two numbers is: %d\n", a.Get())} else {fmt.Println("Both numbers must be non-zero for multiplication.")}}
Lastly, we create the go.mod
file. To create this file, we run the following command on the terminal inside the swig
directory:
go mod init tutorial/swiggo mod tidy
Note: The tutorial/swig
is the user’s directory path.
After running these commands, go.mod
is created inside the swig
folder:
module tutorial/swiggo 1.21.0
Inside the swig
folder, run the go run .
command on the terminal.
package multiplier import "C"
The expected output of the following code is:
The product of two numbers is: 8
Using C++ in Go is more complex than using C in Go. Golang doesn’t support C++ functions directly. However, the solution is using wrappers for C++ code. For this, we use SWIG. SWIG is a tool that generates a wrapper to allow a language to access declarations from other languages. Hence, it can allow Go to use C++ functions in code efficiently.
Free Resources