Search code examples
cparsingcode-generation

Are there any tools for parsing a c header file and extract a function protoype from a c header file


Especially getting the function return type(and if possible whether its a pointer type).

(I'm trying to write auto generation of ioctl/dlsym wrapper libs(to be LD_PRELOAD ed)). A python or ruby library would be preferred but any workable solution is welcome.


Solution

  • I have successfully used Haskells Language.C package from hackage (Haskells answer to CPAN) to do something similar. It will provide you with a complete parse tree of the C (or header) file which can then be traversed to extract the needed information. It should AFAIK also work with #includes #defines and so on.

    I'm afraid I don't have the relevant software installed to test it, but it would go something like this:

    handler (DeclEvent (Declaration d)) =
    do
    let (VarDecl varName declAttr t) = getVarDecl d
    case t of 
         (FunctionType (FunType returnType params isVaradic attrs)) -> 
            do {- varName RETURNS returnType .... -}
             _ -> do return ()
        return ()
    handler _ = 
        do return ()
    
    main = do    
        let compiler = newGCC "gcc"
        ast <- parseCFile compiler Nothing opts cFileName
        case (runTrav newState (withExtDeclHandler (analyseAST ast) handler)) of
            ...
    

    The above might look scary, but you probably won't be needing that many more lines of Haskell to do what you want! I'll gladly share the complete source code I used (~200 lines) if it can be of any help.