Go (Golang) is known for its simplicity, efficiency, and concurrency model, while C++ offers high performance and control over system resources. There are cases where you might want/need to use the simpler interface of Go but with the performance of C++, for instance, when you have legacy C++ libraries or some specific functionality that is not available in Go. In this article, you will learn how to integrate C++ code into Go codebase in the easiest way possible.
Prerequisite
To follow this guide, you will need:
- Go installed on your machine.
- G++ (GNU C++ compiler) installed for compiling C++ code.
- Basic understanding of both Go and C++ programming.
- A working setup of cgo, which is part of Go.
Make sure your environment variables for Go (GOPATH) and g++ are properly set up.
Steps
Step 1: Create C++ Code
The process begins with the C++ code of what you want to include in your Go code. This C++ code you will build onto a shared library in order that Go can call it using cgo.
Create a file named example.cpp:
C++
// example.cpp
#include <iostream>
extern "C" {
// A function that will be called from Go
void helloFromCpp() {
std::cout << "Hello from C++!" << std::endl;
}
}
The extern "C" block ensures the C++ function can be accessed from Go without name mangling.
Step 2: Compile the C++ Code into a Shared Library
In order for Go to use the given C++ code, that code has to be compiled to a shared object file (. so or. dylib).
g++ -c -fPIC example.cpp -o example.o
g++ -shared -o libexample.so example.o
The -fPIC flag is used to generate position-independent code, and -shared creates a shared library.
Step 3: Write Go Code
Now, make a Go file of type main. go in which, integrate the shared H file that is also of C++ language. To use C functions in Go, we use the cgo package to operate and, with some additional reconfiguration, call C++ functions.
Go
// main.go
package main
/*
#cgo LDFLAGS: -L. -lexample
#include <stdio.h>
// Declare the C++ function from the shared library
extern void helloFromCpp();
*/
import "C"
func main() {
// Call the C++ function
C.helloFromCpp()
}
Step 4: Build and Run the Go Program
After writing the Go code, you can compile and run it. Ensure that the shared library (libexample.so) is in the same directory as your Go code.
go run main.go
Code
Here is a full example with both C++ and Go code:
C++ Code (example.cpp):
C++
#include <iostream>
extern "C" {
void helloFromCpp() {
std::cout << "Hello from C++!" << std::endl;
}
}
Go Code (main.go):
Go
package main
/*
#cgo LDFLAGS: -L. -lexample
#include <stdio.h>
extern void helloFromCpp();
*/
import "C"
func main() {
C.helloFromCpp()
}
Output
After running the Go program, the output will be:
Hello from C++!
This demonstrates that the Go code successfully called the C++ function and executed it.
Conclusion
The process of utilizing C++ code in a Golang application is the best method of combining the best functionalities of both. Expectedly, the cgo allows for the creation of C++ callbacks, which means that Go can interface with other C++ libraries or write high-performance functions. In this guide, I have described how to create C++ code, compile it into a shared library, and how to use cgo to call it in Go.
Similar Reads
How to use Ellipsis (...) in Golang?
The three dots (...) in Golang is termed as Ellipsis in Golang which is used in the variadic function. The function that called with the varying number of arguments is known as variadic function. Or in other words, a user is allowed to pass zero or more arguments in the variadic function. fmt.Printf
2 min read
How to Use Go With MongoDB?
MongoDB is an open-source NoSQL database. It is a document-oriented database that uses a JSON-like structure called BSON to store documents like key-value pairs. MongoDB provides the concept of collection to group documents. In this article, we will learn about How to Use Go With MongoDB by understa
15+ min read
How to Use Go with MySQL?
MySQL is an open-source relational database management system based on Structured Query Language(SQL). It is a relational database that organizes data into one or more tables in which data are related to each other. Database Driver: A Database Driver implements a protocol for a database connection.
4 min read
How to Install Golang in VScode?
GO is a compiled programming language developed by Robert Griesemer, Rob Pike, and Ken Thompson at Google. It was introduced in 2009 and is also known as golang. In this article, we are going to see how you can set up Visual Code Studio for Go language Development. We are going to install the necess
3 min read
How to Install Go on Windows?
Prerequisite: Introduction to Go Programming Language Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robe
3 min read
How to Create Modules in Golang?
Go has included support for versioned modules as proposed here since 1.11 with the initial prototype as vgo. The concept of modules in Go was introduced to handle the problem of dependencies within your Go applications. Several packages are collected and combined to form a module which is stored in
3 min read
How to use for and foreach loop in Golang?
There is only one looping construct in Golang, and that is the for loop. The for loop in Golang has three components, which must be separated by semicolons (;), those are:Â The initialization statement: which is executed before the first iteration. e.g. i := 0The condition expression: which is execu
3 min read
How to Install Go on AWS EC2?
EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer.Go is an open-source,
2 min read
How to use strconv.Itoa() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Itoa() function which is equivalent to FormatInt(int64(x), 10). Or in other words, Itoa() function returns the string representation of x
2 min read
How to use strconv.Quote() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a Quote() function which is used to find a double-quoted Go string literal representing str and the returned string uses Go escape sequences
2 min read