Identifying functions in C files and replacing them with a keywordthrough PERL

Discussion in 'Perl Misc' started by IJALAB, Mar 18, 2013.


    IJALAB Guest


    I have to write a parser to go over the C code base and identify all the functions in each file and replace each function name with a keyword, for example, i have a file name
    int func1(struct commandId)
    return ( SUCCESS );
    void func2(struct commandId)
    return ( SUCCESS );
    float func3(struct commandId)
    return ( SUCCESS );
    My intention is to replace func1, func2, func3 with func1_main, func2_main, func3_main....
    The code base is big and there are lot of files and other open close braces in if else statements etc.., so, i would like to know any parser that exist in PERL to do this intended function.

    thanks a lot
    IJALAB, Mar 18, 2013
    1. Advertisements


    Jim Gibson Guest

    I have used Text::Balanced and its extract_delimited() subroutine for
    this type of task. It works OK if your source files are reasonable and
    not pathological. Search for the first '{' in the file, then use the
    extract_delimited() routine to find the matching, closing '}', etc.
    Jim Gibson, Mar 18, 2013
    1. Advertisements

  3. Do you want to keep the existing formatting? If not, the 'dead-easy'
    approach would be to run indent -kr on all of your source files and
    then replace the name in front of the bracketed (parenthesed?) sequence on all lines
    immediately followed by a line with a { in the first column.
    Rainer Weikusat, Mar 18, 2013

    Ted Zlatanov Guest

    BM> Well, Inline::C has a limited C grammar, but I don't know if it will do
    BM> what you want. You may have to start with the grammar in the C standard,
    BM> and Parse::RecDescent.

    BM> If I were doing this I might try mucking around with nm and objdump to
    BM> get the compiler to find the functions for me. gcc -gstabs followed by
    BM> objdump -G on the object file seems to give some useful information (the
    BM> n_desc field of an SLINE entry seems to be a line number).
    BM> Alternatively, ctags -x also looks quite promising.

    According to
    you can use `gcc -fdump-tree-original-raw ./test.c' to dump the AST in a
    pretty easily parseable format like this:

    @43 function_type size: @35 algn: 8 retn: @8
    prms: @48
    @44 parm_decl name: @49 type: @8 scpe: @31
    srcp: test.c:3 argt: @8
    size: @13 algn: 32 used: 0
    @45 identifier_node strg: char lngt: 4

    Perhaps that approach works for the OP? It will tell them exactly where
    the function is declared in the source.

    Ted Zlatanov, Mar 22, 2013
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.