Regex to pull out C function prototype declarations?

前端 未结 8 633
星月不相逢
星月不相逢 2020-11-30 04:48

I\'m somewhere on the learning curve when it comes to regular expressions, and I need to use them to automatically modify function prototypes in a bunch of C headers. Does

8条回答
  •  -上瘾入骨i
    2020-11-30 05:30

    Here's a regular expression that's a good starting point for finding C function names:

    ^\s*(?:(?:inline|static)\s+){0,2}(?!else|typedef|return)\w+\s+\*?\s*(\w+)\s*\([^0]+\)\s*;?
    

    And these are some test cases to validate the expression:

    // good cases
    static BCB_T   *UsbpBufCtrlRemoveBack   (BCB_Q_T *pBufCtrl);
    inline static AT91_REG *UDP_EpIER               (UDP_ENDPOINT_T *pEndpnt);
    int UsbpEnablePort (USBP_CTRL_T *pCtrl)
    bool_t IsHostConnected(void)
    inline AT91_REG *UDP_EpCSR (UDP_ENDPOINT_T *pEndpnt)
    
    // shouldn't match
    typedef void (*pfXferCB)(void *pEndpnt, uint16_t Status);
        else if (bIsNulCnt && bIsBusyCnt)
                return UsbpDump(Buffer, BufSize, Option);
    

    Finally, here's a simple TCL script to read through a file and extract all the function prototypes and function names.

    set fh [open "usbp.c" r]
    set contents [read $fh]
    close $fh
    set fileLines [split $contents \n]
    set lineNum 0
    set funcCount 0
    set funcRegexp {^\s*(?:(?:inline|static)\s+){0,2}(?!else|typedef|return)\w+\s+\*?\s*(\w+)\s*\([^0]+\)\s*;?}
    foreach line $fileLines {
        incr lineNum
        if {[regexp $funcRegexp $line -> funcName]} {
            puts "line:$lineNum, $funcName"
            incr funcCount
        }; #end if
    
    }; #end foreach
    puts "$funcCount functions found."
    

提交回复
热议问题