{"id":4344,"library":"clang","title":"Python Bindings for libclang","description":"The `clang` package provides Python bindings for libclang, enabling programmatic interaction with Clang's C/C++/Objective-C abstract syntax trees (ASTs), parsing source code, and accessing compiler information. It is maintained as part of the broader LLVM project and typically releases in sync with major LLVM versions. The current version is 21.1.7.","status":"active","version":"21.1.7","language":"en","source_language":"en","source_url":"https://github.com/llvm/llvm-project/tree/main/clang/tools/libclang/python","tags":["clang","llvm","compiler","ast","c","c++","bindings","static-analysis"],"install":[{"cmd":"pip install clang","lang":"bash","label":"Install Python bindings"}],"dependencies":[],"imports":[{"symbol":"Index","correct":"from clang.cindex import Index"},{"symbol":"Config","correct":"from clang.cindex import Config"},{"symbol":"Cursor","correct":"from clang.cindex import Cursor"},{"symbol":"TranslationUnit","correct":"from clang.cindex import TranslationUnit"}],"quickstart":{"code":"import os\nfrom clang.cindex import Index, Config, TranslationUnit # type: ignore\n\n# CRITICAL: Ensure libclang (the C++ library) is installed and discoverable.\n# The 'clang' pip package only provides Python wrappers.\n#\n# On macOS (with Homebrew LLVM): \n# Config.set_library_path('/usr/local/opt/llvm/lib')\n# On Linux (e.g., Ubuntu/Debian LLVM-18): \n# Config.set_library_path('/usr/lib/llvm-18/lib')\n# On Windows, ensure 'libclang.dll' is in your PATH or set its full path.\n# Alternatively, set the CLANG_LIBRARY_PATH environment variable.\n\nsource_code = \"\"\"\n#include <stdio.h>\n\nint add(int a, int b) {\n    return a + b;\n}\n\nint main() {\n    printf(\"Hello from Clang AST!\");\n    int result = add(5, 7);\n    return 0;\n}\n\"\"\"\n\ntry:\n    index = Index.create()\n    # Parse the source code from a string. 'main.c' is a dummy name.\n    # args can include compiler flags, e.g., ['-std=c99', '-I/path/to/includes']\n    tu = index.parse('main.c', unsaved_files=[('main.c', source_code)], args=['-x', 'c'])\n\n    # Check for diagnostics (errors, warnings) during parsing\n    if tu.diagnostics:\n        for diag in tu.diagnostics:\n            if diag.severity >= 3: # Error or Fatal\n                print(f\"Diagnostic (Error): {diag.spelling} at {diag.location}\")\n\n    # Walk the AST and print top-level declarations\n    print(\"\\nTop-level declarations:\")\n    for cursor in tu.cursor.get_children():\n        if cursor.location.file and cursor.location.file.name == 'main.c':\n            print(f\"- {cursor.kind.name}: {cursor.spelling} at Line {cursor.location.line}\")\n\n    # Example: Finding the 'main' function and its call to 'add'\n    for cursor in tu.cursor.walk_preorder():\n        if cursor.kind.is_function() and cursor.spelling == 'main':\n            print(f\"\\nFound 'main' function at Line {cursor.location.line}\")\n            for child in cursor.get_children():\n                if child.kind.is_call_expr() and child.spelling == 'add':\n                    print(f\"  -> 'main' calls 'add' at Line {child.location.line}\")\n            break\n\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\n    print(\"Hint: Make sure libclang is installed on your system and its path is correctly configured.\")\n","lang":"python","description":"This quickstart demonstrates how to parse C code from a string, check for diagnostics, and traverse the Abstract Syntax Tree (AST) using `clang.cindex`. The most critical step is ensuring that the underlying `libclang` shared library is installed on your system and discoverable by the Python bindings."},"warnings":[{"fix":"Install `libclang` via your system's package manager (e.g., `apt install libclang-dev` on Debian/Ubuntu, `brew install llvm` on macOS, or LLVM installer on Windows) before running Python code.","message":"The `clang` PyPI package provides Python bindings ONLY. It does NOT include the `libclang` C++ shared library, which is a fundamental dependency. You must install `libclang` separately on your operating system.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Set the `CLANG_LIBRARY_PATH` environment variable to the directory containing `libclang` before running your Python script, or call `clang.cindex.Config.set_library_path('/path/to/libclang/directory')` in your code.","message":"After installing `libclang`, the Python bindings might not find it automatically. You may need to explicitly tell the bindings where to find `libclang.so` (Linux), `libclang.dylib` (macOS), or `libclang.dll` (Windows).","severity":"gotcha","affected_versions":"All versions"},{"fix":"Try to keep the Python `clang` package version in sync with your system's `libclang` version. For example, `pip install 'clang==18.*'` if you have LLVM 18 installed. Downgrade/upgrade `libclang` or the Python bindings if problems persist.","message":"There can be compatibility issues if the version of the `clang` Python package does not match the version of the system `libclang` installed. Mismatches can lead to crashes, incorrect parsing, or unexpected behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always refer to the official LLVM `libclang` Python binding documentation or examples corresponding to your LLVM version when upgrading. Test thoroughly after upgrading major versions.","message":"The `clang.cindex` API, being a binding to a C++ library, can have subtle breaking changes between major LLVM versions (e.g., how AST nodes are iterated, new cursor kinds, or changes in diagnostic information structure).","severity":"breaking","affected_versions":"Major version bumps (e.g., 17.x to 18.x)"},{"fix":"Pass all necessary compiler flags (e.g., `-I`, `-D`, `-std=c++17`, `-x c++`) as a list of strings to the `args` parameter of `index.parse()`.","message":"Correctly configuring compiler arguments (e.g., include paths, language standard, preprocessor definitions) is crucial for accurate parsing of C/C++ source code, especially for complex projects.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-12T00:00:00.000Z","next_check":"2026-07-11T00:00:00.000Z"}