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.
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.
Before we dive in, make sure you have:
To call C code in your Go project, follow these steps:
$ mkdir cgo_example
$ cd cgo_example
$ go mod init github.com/yourusername/cgo_example$ touch c_code.cmain.go file, import the "C" package and include the C file using the #cgo directive:package main
/*
#include "c_code.h"
*/
import "C"
func main() {
// Your Go code here
}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_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);
}To link the C code with your Go project, use the CGO_ENABLED=0 flag when building the project:
$ go build -buildmode=c-shared -o c_library.so c_code.cThis command generates a shared library (.so on Linux) containing the C code.
Update the main.go file to import the C library:
// Import the C library
#include "C"
// Import the C functions
import "C"
func main() {
// Call the C function
C.greet(C.CString("John Doe"))
}Build the project:
$ go build -o mainRun the compiled Go program:
$ ./mainYou should see the output:
Hello, John Doe! Welcome to CGO in Golang.
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! 🚀