微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 检索有关预处理器指令的信息

我最近开始使用libclang来解析C文件.我遇到的问题是,显然,libclang会在生成AST之前启动预处理程序.我想禁止预处理器运行,而是提供预处理指令在文件中的信息…

我使用以下python脚本(cindex.py和libclang)

import codecs
from clang.cindex import *

class SourceFile(object):
    def __init__(self,path):
        with codecs.open(path,'r','utf-8') as file:
            self.file_content = file.read()

        index = Index.create()
        root_node = index.parse(path)

        for included in root_node.get_includes():
            print included.include

        self.print_declerations(root_node.cursor)

    def print_declerations(self,root,recurse=True):
        print root.kind.name,root.spelling
        if root.kind.is_declaration():
            node_def = root.get_deFinition()
            if node_def is not None:
                start_offset = node_def.extent.start.offset
                end_offset = node_def.extent.end.offset + 1
                print self.file_content[start_offset:end_offset],'\n'

        if recurse:
            for child in root.get_children():
                self.print_declerations(child,False)

if __name__ == '__main__':
    path = 'Sample.cpp'
    print 'Translation unit:',path
    source = SourceFile(path)

哪些输出

Translation unit: Sample.cpp
/mingw/include\stdio.h
/mingw/include\_mingw.h
/mingw/include\sys/types.h
TRANSLATION_UNIT None
TYPEDEF_DECL __builtin_va_list

STRUCT_DECL _iobuf

TYPEDEF_DECL FILE

VAR_DECL _iob
UNEXPOSED_DECL 

FUNCTION_DECL main
int main()
{
    printf(HELLO_WORLD);
    return 0;
}

对于以下C代码

#include <stdio.h>
#define HELLO_WORLD "HELLO!"

int main()
{
    printf(HELLO_WORLD);
    return 0;
}

我想要的是在代码中为我的#define获取DEFINE_DECL HELLO_WORLD(目前我什么都没有).当然也可以得到类似的我的#include的声明.这可能吗?

编辑:基本上,我想解析文件,而不扩展预处理指令.

解决方法

前几天我在#llvm freenode irc频道上问了同一个问题.答案是“宏不是AST的一部分,所以你不能”,但最可能的是“-fSyntax-only”选项和clang插件而不是libclang可能会帮助你.

编辑:看起来现在实际上是可以的,请参阅bradtgmurray的回答

原文地址:https://www.jb51.cc/c/114890.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐