0

I am trying to get list of all macro definitions in a c header file by using pycparser.

Can you please help me on this issue with an example if possible?

Thanks.

  • 1
    In the simplest form you can use grep can you not? What's the exact use case? That is, when you say you want to LIST all macro definitions, do you mean in the way CPP would or do you mean you just want to list them ? – Ahmed Masud Jun 19 '13 at 03:57
  • I know that pycparser uses cpp and i managed to get list of struct definitions in a c file. however i could not find the way to get all #define macros in a h file. For now, i just parse the header file with python but this is not what i want. thanks. – user1587140 Jun 20 '13 at 16:01

1 Answers1

2

Try using pyparsing instead...

from pyparsing import *

# define the structure of a macro definition (the empty term is used 
# to advance to the next non-whitespace character)
macroDef = "#define" + Word(alphas+"_",alphanums+"_").setResultsName("macro") + \
            empty + restOfLine.setResultsName("value")
with open('myheader.h', 'r') as f:
    res = macroDef.scanString(f.read())
    print [tokens.macro for tokens, startPos, EndPos in res]

myheader.h looks like this:

#define MACRO1 42
#define lang_init ()  c_init()
#define min(X, Y)  ((X) < (Y) ? (X) : (Y))

output:

['MACRO1', 'lang_init', 'min']

The setResultsName allows you to call the portion you want as a member. So for your answer we did tokes.macro, but we could have just as easily accessed the value as well. I took part of this example from Paul McGuire's example here

You can learn more about pyparsing here

Hope this helps

onetwopunch
  • 3,279
  • 2
  • 29
  • 44