libclang Python Bindings

18.1.1 · active · verified Thu Apr 09

libclang provides Python bindings for Clang, the LLVM project's C, C++, and Objective-C compiler front-end. It allows programmatic access to Clang's AST (Abstract Syntax Tree), diagnostics, and other compiler functionalities. The `libclang` PyPI package, currently at version 18.1.1, mirrors the official LLVM project's Python bindings to simplify installation and is released in sync with major LLVM versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse C/C++ code, check for diagnostics, iterate through the Abstract Syntax Tree (AST) to find function declarations and their arguments, and access tokens. When installed via the official `libclang` wheel, the library attempts to automatically locate the necessary `libclang` shared library, making manual configuration via `Config.set_library_file()` often unnecessary.

from clang.cindex import Index, TranslationUnit

# Source code to parse
source_code = """
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main() {
    printf("Sum: %d\n", add(5, 3));
    return 0;
}
"""

# Create an index
index = Index.create()

# Parse the source code from a string. For files, use Index.parse('path/to/file.c')
tu = index.parse('test.c', unsaved_files=[('test.c', source_code)])

# Check for diagnostics (errors/warnings)
for diagnostic in tu.diagnostics:
    print(f"Diagnostic: {diagnostic}")

# Iterate through the AST to find functions
print("\nFunctions found:")
for cursor in tu.cursor.get_children():
    if cursor.kind == TranslationUnit.CursorKind.FUNCTION_DECL:
        print(f"  Function: {cursor.spelling}, return type: {cursor.result_type.spelling}")
        for arg in cursor.get_arguments():
            print(f"    Argument: {arg.spelling}, type: {arg.type.spelling}")

print("\nFirst 10 tokens:")
for token in tu.get_tokens(extent=tu.cursor.extent)[:10]:
    print(f"  Token: '{token.spelling}' (kind: {token.kind})")

view raw JSON →