clang_createTranslationUnitFromSourceFile()和C ++源代码

时间:2019-05-26 21:12:57

标签: c++ clang

我试图在libclang的帮助下确定C ++源代码中的数据类型。我的程序是

#include <stdio.h>
#include <stdlib.h>
#include <clang-c/Index.h>

int main(int argc, char *argv[])
{
    CXIndex index;
    CXTranslationUnit tu;
    CXFile file;
    CXSourceLocation loc;
    CXCursor cursor, def;
    CXType type;
    CXString typesp;
    const char *types;

    char const *args[2] = {"-x", "c++"};
    index = clang_createIndex(0, 0);
    tu = clang_createTranslationUnitFromSourceFile(index, argv[1],
            2, args, 0, NULL);
    file = clang_getFile(tu, argv[1]);
    loc = clang_getLocation(tu, file, atoi(argv[2]), atoi(argv[3]));
    cursor = clang_getCursor(tu, loc);

    if (clang_isPreprocessing(cursor.kind))
        printf("Preprocessor\n");
    else {
        def = clang_getCursorDefinition(cursor);
        if (clang_Cursor_isNull(def))
            type = clang_getCursorType(cursor);
        else 
            type = clang_getCursorType(def);
        typesp = clang_getTypeSpelling(type);
        types = clang_getCString(typesp);
        printf("%s\n", types);
        clang_disposeString(typesp);
    }
    clang_disposeTranslationUnit(tu);
    clang_disposeIndex(index);
}

并测试我提供给程序的源代码helloworld.cpp

#include <iostream>

int main()
{
    long t;
    t = 0;
    std::cout << "Hello World!";
}

当我将测试源代码传递给命令行参数(例如./program helloworld.cpp 7 2)时,它无法确定变量t的类型。我在使用gdb的程序中观看了cursor变量的值,它是{kind = CXCursor_NoDeclFound, xdata = 0, data = {0x0, 0x0, 0x0}}。但是,如果我为helloworld.cpp生成AST文件并使用clang_createTranslationUnit()而不是clang_createTranslationUnitFromSourceFile(),一切正常。

我做错了什么,或者clang_createTranslationUnitFromSourceFile()不支持C ++代码的解析?我的clang版本是8.0.0

0 个答案:

没有答案