How to use C++ in Go
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.,
Prerequisite
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
Steps
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
swigthat has one foldermultiplierand a filemain.goin it. We will begin with creating the primary files inside themultiplierfolder.Create a C++ header file,
multiplier.hpp. Inside it, create a classMultiplier. The public section of the class will have a constructorMultiplier()that initializes a private member variable_vwith the value 1. A public methodMultiplywill be declared, which takes an integervas an argument. This function will be responsible for performing multiplication with the private variable_v. Another methodGet()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 filemultiplier.hpp. Implement theMultiply()andGet()method of classMultiplercreated 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 itmultiplier. 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 includemultiplier.hppseparately to ensure that the C++ class and functions declared inmultiplier.hppare 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 theswigdirectory. In this file, we will pass two numbers we want to multiply to ourMultiply()function. To fulfill the initial constraints of the problem, i.e., both the numbers should be non-zero, we will implement a check usingif 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.modfile. To create this file, we run the following command on the terminal inside theswigdirectory:
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
swigfolder, run thego run .command on the terminal.
Code
package multiplier import "C"
Output
The expected output of the following code is:
The product of two numbers is: 8
Conclusion
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