簡體   English   中英

如何使用 libclang 從 C++ 源文件中檢索所有函數調用?

[英]How do I retrieve all function calls from C++ source files with libclang?

我正在學習用python-libclang解析一些 C++ 源文件,到目前為止,我有一個可以部分實現我希望的腳本:

import clang.cindex

idx = clang.cindex.Index.create()
tu = idx.parse('example.cpp', args='-xc++ --std=c++11'.split())
for cursor in tu.cursor.walk_preorder():
    print("`{}` --> {}".format(cursor.spelling, cursor.kind))

這個腳本可以解析一個example.cpp

// example.cpp
// I know this is incomplete but this is all I got: some incomplete files
int main()
{
    Thing *thing = new Thing();
    thing->DoSomething();
    return 0;
}

並打印出來:

`example.cpp` --> CursorKind.TRANSLATION_UNIT
`main` --> CursorKind.FUNCTION_DECL
`` --> CursorKind.COMPOUND_STMT
`` --> CursorKind.DECL_STMT
`thing` --> CursorKind.VAR_DECL
`` --> CursorKind.RETURN_STMT
`` --> CursorKind.INTEGER_LITERAL

然而,沒有關於函數DoSomething()的信息。 如何從源文件中找到所有函數調用(希望是它們的完全限定名稱)?

例如,我如何得到一個Thing::DoSomething ,或者至少是一個DoSomething


我已經閱讀並嘗試了以下示例

但他們都沒有得到我想要的。

歡迎推薦任何其他簡單的工具來解析 C++ 源文件。

您的代碼無法按預期工作,因為Thing缺少定義,甚至沒有聲明。 Clang 沒有將其解析為函數調用,因為就它而言,代碼格式不正確。 要查看,請嘗試添加一個聲明,例如

struct Thing { void DoSomething(); };

你會看到你丟失的函數調用看起來像:

`Thing` --> CursorKind.TYPE_REF
`DoSomething` --> CursorKind.CALL_EXPR
`DoSomething` --> CursorKind.MEMBER_REF_EXPR

(使用 LLVM 14 測試)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM