Article by Ayman Alheraki on January 11 2026 10:32 AM
Yes, you can use C++ to write libraries or packages that can be used in Python. This method is particularly useful when certain parts of an application need to be written in C++ to benefit from its high performance or memory control, while the rest of the application is developed using Python for ease and speed of development.
The most common ways to create C++ packages that work with Python include tools like SWIG, Boost.Python, or Pybind11. I will explain in detail how to use Pybind11 to create a C++ package that can be called from Python.
Pybind11 is a simple and efficient library used for integrating C++ code with Python.
It allows you to write C++ code and export functions or classes to Python easily, without much configuration.
Python installed on your machine.
A C++ compiler like g++ or clang.
Install the Pybind11 library.
To install Pybind11, you can use the pip package manager:
xxxxxxxxxxpip install pybind11First, write a simple C++ program containing functions that you want to call from Python.
file: example.cpp
// A simple function that adds two numbersint add(int a, int b) { return a + b;}
PYBIND11_MODULE(example, m) { m.doc() = "A simple example module"; // Module description m.def("add", &add, "A function that adds two numbers"); // Defining the function for Python}If you are using CMake to build the project, you can create a CMakeLists.txt file as follows:
file: CMakeLists.txt
cmake_minimum_required(VERSION 3.4...3.18)project(example)
set(CMAKE_CXX_STANDARD 11)
find_package(pybind11 REQUIRED)
pybind11_add_module(example example.cpp)To manually compile the project using g++, run the following commands:
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)Once the package is built, you will have a shared file example.so (or example.pyd on Windows), which you can import and use in Python.
file: test.py
import example
# Calling the add function from Pythonresult = example.add(3, 5)print(f"The result of add(3, 5) is: {result}")Then execute the Python file:
python test.pyThe result of add(3, 5) is: 8Exporting More Functions: You can export additional functions or classes using the same method as the add function.
Working with Classes: You can also export entire C++ classes to Python.
Performance: This type of binding is very useful when you need to optimize performance in certain parts of your Python-based application using C++.
Conclusion: Integrating C++ with Python through tools like Pybind11 gives you the ability to write fast and efficient code in C++ while retaining the ease of use and development speed of Python. This hybrid programming approach is particularly beneficial in applications requiring high performance, such as data processing, heavy computations, or hardware control.