CGO isn’t a beast

The formal info about CGO is here. CGO is a Go tool very useful that you could find in many projects but if you read some articles, they say that CGO is dangerous and your should avoid it. Is it that true?

What is CGO in a simple way? Basically is a tool that allows us to write C code with Go syntax. In other words in C inside Go. Okay, simple but… why do we need it?

The main use of CGO is that it allows us to link our code to another code written in other languages like C++, Rust or even Python bidirectionally. What I mean is that we can use Go code to be used in other languages, or other language codes to be use in our Go code.

// #include <stdio.h>
// #include <errno.h>
import "C"

The main use cases are:

  • Link a dynamic C-shared library (dll, os) to our code.
  • Link statically archive C-shared libraries to our code.

We could write code in CGO and run it as it, but even though that is possible it doesn’t make sense. If you need to write C code, do it in C directly and not in CGO.

Some recommendations we keep in mind though:

  • This is C, if you allocate memory, you need to free it.
  • Use the modern approach to C. Use a central allocator, and do not allocate memory here and there in you code.
  • Hiding information (OOP) is possible using the header. You can define the struct with no field in the header and define then in the implementation file. This is a good practice to have a clean code.

In the next post I will show an example of how to link a C-shared library to our Go code.

 

Adan J. Suarez

Software Engineering and IT consultancy.


By Adan J. Suarez, 2023-02-04