Build a Python Extension Module with CMake
In this article
This guide shows you how to build a Python extension module (a compiled .pyd or .so file) using CMake, the cross-platform build system. This approach gives you fine control over compilation flags, dependencies, and multi-language projects, and it works reliably across Windows, macOS, and Linux. You’ll end up with a module you can import directly in Python, just like any pure-Python package.
What You'll Need
- A C or C++ compiler (GCC, Clang, or MSVC) installed and working.
- CMake version 3.15 or newer.
- Python 3.6 or newer, with the development headers installed (on most systems, install the
python3-devorpython3-develpackage). - Basic familiarity with the command line and a text editor.
Step-by-Step
- Create a project directory with two subfolders:
srcfor your C/C++ source andbuildfor CMake output. For example:mkdir mymodule && cd mymodule && mkdir src build. - Write your extension source code. In
src/mymodule.c, create a minimal Python extension. Here’s a simple one that adds two integers:#include <Python.h> static PyObject* add(PyObject* self, PyObject* args) { int a, b; if (!PyArg_ParseTuple(args, "ii", &a, &b)) return NULL; return PyLong_FromLong(a + b); } static PyMethodDef methods[] = { {"add", add, METH_VARARGS, "Add two integers."}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "mymodule", NULL, -1, methods }; PyMODINIT_FUNC PyInit_mymodule(void) { return PyModule_Create(&moduledef); }Note: the init function must be namedPyInit_<module_name>exactly. - Create the CMakeLists.txt in the project root. This file tells CMake how to find Python and build the module. A minimal version:
cmake_minimum_required(VERSION 3.15) project(mymodule LANGUAGES C) find_package(Python3 REQUIRED COMPONENTS Development.Module) Python3_add_library(mymodule MODULE src/mymodule.c) set_target_properties(mymodule PROPERTIES PREFIX "")
ThePREFIX ""removes thelibprefix that CMake normally adds, so you getmymodule.soinstead oflibmymodule.so. - Configure the build. From the project root, run:
cmake -S . -B build. This tells CMake to look for the source in the current directory and put generated files inbuild. - Build the module. Run:
cmake --build build. On Windows with MSVC, you may need to specify the configuration:cmake --build build --config Release. - Locate the output. The compiled module will be in
build/(orbuild/Releaseon Windows). It will be namedmymodule.soon Linux/macOS ormymodule.pydon Windows. - Test the module. From the build directory, run Python and import it:
python -c "import mymodule; print(mymodule.add(2,3))"
You should see5. - Install the module (optional). To make it importable from anywhere, copy the .so/.pyd file to a directory on your
PYTHONPATH, or add an install rule in CMake:install(TARGETS mymodule LIBRARY DESTINATION lib/python3.11/site-packages)
Adjust the Python version path as needed.
Common Mistakes
- Wrong init function name. If your module is named
mymodule, the function must bePyInit_mymodule. A typo causes an import error. - Forgetting
PREFIX "". Without it, CMake produceslibmymodule.so, which Python cannot import because it looks formymodule.so. - Using
find_package(PythonLibs)instead ofPython3. The olderPythonLibsis deprecated and often picks the wrong Python version. Usefind_package(Python3 REQUIRED COMPONENTS Development.Module). - Not specifying the language. If you forget
LANGUAGES Cin the project command, CMake may default to CXX and fail to compile C code. - Building in the source tree. Running CMake directly in the source directory pollutes it. Always use a separate build directory.
Tips
- Use
Python3_add_libraryinstead ofadd_librarybecause it automatically sets the correct suffix (.pyd on Windows, .so on Unix) and links against Python’s import library. - For C++ extensions, change
LANGUAGES CtoLANGUAGES CXXand name your source file with a .cpp extension. You’ll also need to wrap the Python headers inextern "C"if you include them in a C++ file. - To support multiple Python versions, use
find_package(Python3 COMPONENTS Development.Module)(without REQUIRED) and check if it was found. - Add
set(CMAKE_BUILD_TYPE Release)before the project command to get optimized code by default. - If you plan to distribute your module, consider using
scikit-build-coreorsetuptoolswith CMake integration, but for a standalone extension, plain CMake is sufficient.
Troubleshooting
- ImportError: dynamic module does not define module export function. Your init function name is wrong or the module name in
PyModuleDefdoesn’t match the file name. Double-check both. - ImportError: undefined symbol: PyInit_mymodule. This usually means the module was compiled without linking to Python, or the symbol is hidden. Ensure you used
Python3_add_libraryand not a plainadd_library. - CMake cannot find Python. On Ubuntu, install
python3-dev; on Fedora,python3-devel; on macOS, install the Command Line Tools and ensure Python is from python.org or Homebrew. Then rerun CMake. - Build succeeds but import fails with “No module named ‘mymodule’”. The .so file isn’t in your current directory or on
PYTHONPATH. Navigate to the build directory or copy the file to a location Python searches. - Windows: LNK1104 cannot open file ‘python311.lib’. This means CMake didn’t find the Python import library. Make sure you have the Python development files installed (check “Add Python to PATH” and “Download debugging symbols” during installation). Re-run CMake after installing.
- Compiler errors about missing Python.h. The Python headers are not installed. Install the development package for your Python version (e.g.,
python3-devon Debian/Ubuntu).
Frequently Asked Questions
Can I use CMake with C++ extensions?
Yes. Change LANGUAGES C to LANGUAGES CXX, name your source file with a .cpp extension, and wrap the Python.h include in extern "C" { ... } if needed. The rest of the process is identical.
How do I make the module importable from anywhere?
Copy the compiled .so/.pyd file to a directory listed in sys.path (e.g., site-packages), or set the PYTHONPATH environment variable to include the build directory.
Can I build for multiple Python versions?
Yes, but you need to run CMake separately for each Python version, using a separate build directory (e.g., build-py38, build-py39). Each run will link against the Python found in your PATH or specified via -DPython3_EXECUTABLE.
What is the difference between a module and a package?
A module is a single .so/.pyd file you import directly. A package is a directory containing an __init__.py and possibly multiple modules. This guide builds a single module; to make a package, place the .so file inside a directory with an __init__.py.
Why does my module have a “lib” prefix?
CMake adds a lib prefix to shared libraries by default. The set_target_properties(... PREFIX "") line removes it, which is required for Python to find the module.
Can I use this with PyPy or other Python implementations?
Yes, as long as the implementation provides a CPython-compatible C API and development headers. CMake’s find_package(Python3) can point to the PyPy executable, but you may need to set Python3_EXECUTABLE manually.