Skip to content

Joris Vergeer

Just some software engineer with some skills

Menu
  • Home
Menu

[Python][Clang] Extract variabele value from a c++ file in python

Posted on January 17, 2023February 27, 2023 by joris

Once in a while you want to extract some values from a source file. For example if you want to extract a version number from code to process in a CI server.

This example uses the python clang bindings to parse a cpp file and extracts a version number form it.

This example used some assumptions about what the code looks like but you can easily modify it to fit your needs.

Lets assume the following content to be available in a version.cpp file

...
static const int major = 1;
static const int minor = 10;
static const int revision = 11;
...

You can use the following python snippet to extract this and format it nicely to stdout.

from clang.cindex import *

# Initialize the Clang index
index = Index.create()

# Parse the C++ file
tu = index.parse('version.cpp')

# Find the variable of interest
major = None
minor = None
revision = None

for cursor in tu.cursor.walk_preorder():
    if cursor.kind == CursorKind.VAR_DECL :
        if cursor.spelling == 'major':
            major = [t.spelling for t in cursor.get_tokens()][-1]
        if cursor.spelling == 'minor':
            minor = [t.spelling for t in cursor.get_tokens()][-1]
        if cursor.spelling == 'revision':
            revision = [t.spelling for t in cursor.get_tokens()][-1]

print(major + '.' + minor + '.' + revision)

This nicely outputs 1.10.11 to stdout

Hope someone finds this example helpful.

  • clang
  • python
  • Work

    Currently working for and owner of RetailEntertainment B.V.
    • MKB-Muziek
    • Zorgscherm
    • Zorgstand
    • [Hashicorp Vault/PostgreSQL] Cleanup of roles with permissions and ownership
    • [C++/QT/OpenSSL/JWT] Minimalistic implementation to create a signed JTW token.
    • [C++/QT] QFuture delay method
    • [Vite] Copy vite build output to destination directory
    • [Python][Clang] Extract variabele value from a c++ file in python
    • May 2024 (1)
    • March 2023 (2)
    • February 2023 (1)
    • January 2023 (1)
    • July 2020 (1)
    • November 2019 (1)
    • May 2019 (1)
    • March 2019 (2)
    • DevOps
    • Programming
    • Uncategorized
    • Web

    Meta

    • Log in
    • Entries feed
    • Comments feed
    • WordPress.org
    © 2025 Joris Vergeer | Powered by Minimalist Blog WordPress Theme