{"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":"python","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,"search_vec":"'/objective-c':20 '21.1.7':55 'abstract':21 'access':29 'analysi':65 'ast':24,59 'bind':2,10,62 'broader':39 'c':60,61 'c/c':19 'clang':6,17,56 'code':27 'compil':30,58 'current':52 'enabl':13 'inform':31 'interact':15 'libclang':4,12 'llvm':40,49,57 'maintain':34 'major':48 'packag':7 'pars':25 'part':36 'programmat':14 'project':41 'provid':8 'python':1,9 'releas':44 'sourc':26 'static':64 'static-analysi':63 'sync':46 'syntax':22 'tree':23 'typic':43 'version':50,53","created_at":"2026-04-12T08:51:45.757480+00:00","updated_at":"2026-04-16T02:15:27.474597+00:00","problems":[{"fix":"Ensure the LLVM/Clang development packages are installed (e.g., `apt-get install libclang-dev` on Debian/Ubuntu, `brew install llvm` on macOS). Explicitly set the path to the library in your Python script: `from clang.cindex import Config; Config.set_library_file('/path/to/libclang.so')` (or `.dll`/`.dylib` as appropriate). If you installed `libclang` via pip, verify its installation and check the package documentation for specific setup instructions if the automatic discovery fails.","cause":"The Python `clang` bindings cannot locate the `libclang` shared library, which is a core dependency. This can be due to `libclang` not being installed, not being in the system's dynamic library path (LD_LIBRARY_PATH on Linux, PATH on Windows, DYLD_LIBRARY_PATH on macOS), or an architectural mismatch (32-bit vs. 64-bit) between Python and libclang. (The error might also show as 'Could not find module 'libclang.dll'' on Windows or '.dylib' on macOS).","error":"LibclangError: libclang.so: cannot open shared object file: No such file or directory."},{"fix":"Install the `clang` package using pip: `pip install clang`. If you are using a virtual environment, ensure it is activated. Verify that the Python interpreter you are running is the one where the package was installed.","cause":"The `clang` Python package or its `cindex` submodule is not found by the Python interpreter. This typically indicates that the package was not installed correctly or installed into a Python environment that is not currently active.","error":"ModuleNotFoundError: No module named 'clang.cindex'"},{"fix":"Access children by iterating over the `Cursor` object itself, or by calling `get_children()` as an iterator. For example: `for child in cursor.get_children():`. Ensure you are using a Python 3 compatible version of the `clang` bindings, as some older versions had compatibility issues.","cause":"This error occurs when attempting to access `get_children` in a way that is inconsistent with the `clang` Python bindings' API, or when the `Cursor` object does not have children (e.g., for certain kinds of AST nodes or due to parsing issues with complex C++ constructs like template instantiations). The Python bindings typically provide children via iteration, not direct method calls for 'get_children' as a function. It can also sometimes be related to Python 2 vs. Python 3 compatibility in older versions of the bindings.","error":"AttributeError: 'Cursor' object has no attribute 'get_children'"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"21.1.7","cli_name":"","cli_version":null,"type":"library","homepage":"http://clang.llvm.org/","github":null,"docs":null,"changelog":null,"pypi":"https://pypi.org/project/clang/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["devops","data"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-29","next_check":"2026-07-28","install_tag":null}}