Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the function declaration or definitions using regex

Tags:

python

regex

I want to get only function prototypes like

int my_func(char, int, float)
void my_func1(void)
my_func2()

from C files using regex and python.

Here is my regex format: ".*\(.*|[\r\n]\)\n"

like image 942
user116391 Avatar asked Jun 03 '09 06:06

user116391


2 Answers

This is a convenient script I wrote for such tasks but it wont give the function types. It's only for function names and the argument list.

# Exctract routine signatures from a C++ module
import re

def loadtxt(filename):
    "Load text file into a string. I let FILE exceptions to pass."
    f = open(filename)
    txt = ''.join(f.readlines())
    f.close()
    return txt

# regex group1, name group2, arguments group3
rproc = r"((?<=[\s:~])(\w+)\s*\(([\w\s,<>\[\].=&':/*]*?)\)\s*(const)?\s*(?={))"
code = loadtxt('your file name here')
cppwords = ['if', 'while', 'do', 'for', 'switch']
procs = [(i.group(2), i.group(3)) for i in re.finditer(rproc, code) \
 if i.group(2) not in cppwords]

for i in procs: print i[0] + '(' + i[1] + ')'
like image 190
Nick Dandoulakis Avatar answered Nov 14 '22 22:11

Nick Dandoulakis


See if your C compiler has an option to output a file of just the prototypes of what it is compiling. For gcc, it's -aux-info FILENAME

like image 33
ysth Avatar answered Nov 14 '22 23:11

ysth