CGO Calling C Code in Golang 🎯

beginner
8 min

CGO Calling C Code in Golang 🎯

Welcome to this comprehensive guide on CGO (C Go)! In this lesson, we'll dive into how to call C code from Golang. By the end of this tutorial, you'll be able to leverage the power of both worlds – Golang's simplicity and C's efficiency – in your projects.

Why CGO Matters 📝

CGO allows you to write C code and include it directly in your Golang projects. This is beneficial when you need to access low-level system functionality, optimize performance-critical parts, or reuse existing C libraries.

Prerequisites ✅

Before we dive in, make sure you have:

  1. Installed Go (Golang) on your system: Official Installation Guide
  2. Familiarity with the basics of Golang: Golang Tour
  3. Basic knowledge of C programming: C Programming Tutorial

Setting Up the Environment 💡

To call C code in your Go project, follow these steps:

  1. Create a new Go project:
sh
$ mkdir cgo_example $ cd cgo_example $ go mod init github.com/yourusername/cgo_example
  1. Create a new C file and write your C code:
sh
$ touch c_code.c
  1. In the main.go file, import the "C" package and include the C file using the #cgo directive:
go
package main /* #include "c_code.h" */ import "C" func main() { // Your Go code here }

The C File (c_code.c) 💡

Write your C code in the c_code.c file. Make sure to include function prototypes in a separate header file (c_code.h).

Here's a simple example:

c
// c_code.h #ifndef C_CODE_H #define C_CODE_H void greet(char* name); #endif // c_code.c #include "c_code.h" void greet(char* name) { printf("Hello, %s! Welcome to CGO in Golang.\n", name); }

Linking the C Code 💡

To link the C code with your Go project, use the CGO_ENABLED=0 flag when building the project:

sh
$ go build -buildmode=c-shared -o c_library.so c_code.c

This command generates a shared library (.so on Linux) containing the C code.

Including the C Library in Go 💡

Update the main.go file to import the C library:

go
// Import the C library #include "C" // Import the C functions import "C" func main() { // Call the C function C.greet(C.CString("John Doe")) }

Building the Project 💡

Build the project:

sh
$ go build -o main

Running the Program 💡

Run the compiled Go program:

sh
$ ./main

You should see the output:

Hello, John Doe! Welcome to CGO in Golang.
Quick Quiz
Question 1 of 1

What does CGO allow you to do in Golang projects?


Keep practicing and experimenting with CGO to create powerful, efficient, and high-performance applications. Happy coding! 🚀