This project demonstrates how to create a Go program that calls C++ functions through CGO, resulting in a single binary executable.
cpplib.hpp- C++ header file with function declarationscpplib.cpp- C++ implementation of the library functionsmain.go- Go program that calls C++ functionsMakefile- Build system for the entire project
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
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- The Makefile first compiles the C++ code into a static library
(
libcpplib.a) - The Go program uses CGO directives to statically link against this library
- The final result is a single, completely static binary executable
(
cgo-demo) - The Go program demonstrates calling various C++ functions with different data types
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.astatic library - Include the C++ standard library and math library
- Include our custom header file
- 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
get_greeting(name): Returns a greeting string with the given namestring_length(str): Returns the length of a stringrepeat_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