CGO + C++ Library Example

This project demonstrates how to create a Go program that calls C++ functions through CGO, resulting in a single binary executable.

Project Structure

  • cpplib.hpp - C++ header file with function declarations
  • cpplib.cpp - C++ implementation of the library functions
  • main.go - Go program that calls C++ functions
  • Makefile - Build system for the entire project

Features

The C++ library provides various functions with different argument and return types:

  • Integer operations: add, multiply, factorial
  • String operations: get_greeting, string_length, repeat_string
  • Float operations: divide, power
  • Array operations: reverse_array, sum_array
  • Boolean operations: is_even, is_positive

Using the Makefile

This Makefile will automatically install Go inside the working directory. It assumes G++ is installed.

# Build the binary
make build

# Build and run the binary
make run

# Clean the build artifacts
make clean

# Clean the Go cache
make distclean

How It Works

  1. The Makefile first compiles the C++ code into a static library (libcpplib.a)
  2. The Go program uses CGO directives to statically link against this library
  3. The final result is a single, completely static binary executable (cgo-demo)
  4. The Go program demonstrates calling various C++ functions with different data types

CGO Directives

The Go program uses these CGO directives:

/*
#cgo CXXFLAGS: -std=c++11
#cgo LDFLAGS: -L. -lcpplib -lstdc++
#include "cpplib.hpp"
*/
import "C"

This tells the Go compiler to:

  • Use C++11 standard
  • Link against the local libcpplib.a static library
  • Include the C++ standard library and math library
  • Include our custom header file

Notes

  • The C++ functions are wrapped in extern "C" to ensure C linkage
  • Memory management is handled properly with C.free() for C strings
  • The build process creates a static library that gets fully linked into the final binary
  • The resulting executable is completely self-contained with no external dependencies

Function Details

String Operations

  • get_greeting(name): Returns a greeting string with the given name
  • string_length(str): Returns the length of a string
  • repeat_string(str, times): Returns the input string repeated the specified number of times
    • Handles edge cases: empty strings, zero/negative times return empty strings
    • Efficiently manages memory for repeated strings