Automatically Generate C Code From Header

后端 未结 3 1088
庸人自扰
庸人自扰 2021-02-15 19:01

I want to generate empty implementations of procedures defined in a header file. Ideally they should return NULL for pointers, 0 for integers, etc, and, in an ideal world, also

3条回答
  •  礼貌的吻别
    2021-02-15 19:17

    so, i'm going to mark the ea suggestion as the "answer" because i think it's probably the best idea in general. although i think that the cmock suggestion would work very well in tdd approach where the library development was driven by test failures, and i may end up trying that. but for now, i need a quicker + dirtier approach that works in an interactive way (the library in question is a dynamically loaded plugin for another, interactive, program, and i am trying to reverse engineer the sequence of api calls...)

    so what i ended up doing was writing a python script that calls pycparse. i'll include it here in case it helps others, but it is not at all general (assumes all functions return int, for example, and has a hack to avoid func defs inside typedefs).

    from pycparser import parse_file
    from pycparser.c_ast import NodeVisitor
    
    
    class AncestorVisitor(NodeVisitor):
    
        def __init__(self):
            self.current = None
            self.ancestors = []
    
        def visit(self, node):
            if self.current:
                self.ancestors.append(self.current)
            self.current = node
            try:
                return super(AncestorVisitor, self).visit(node)
            finally:
                if self.ancestors:
                    self.ancestors.pop(-1)
    
    
    class FunctionVisitor(AncestorVisitor):
    
        def visit_FuncDecl(self, node):
            if len(self.ancestors) < 3: # avoid typedefs
                print node.type.type.names[0], node.type.declname, '(',
                first = True
                for param in node.args.params:
                    if first: first = False
                    else: print ',',
                    print param.type.type.names[0], param.type.declname,
                print ')'
                print '{fprintf(stderr, "%s\\n"); return 0;}' % node.type.declname
    
    
    print '#include "myheader.h"'
    print '#include '
    ast = parse_file('myheader.h', use_cpp=True)
    FunctionVisitor().visit(ast)
    

提交回复
热议问题