Functions from header files

Updated: May 19, 2009

I always think if we have a reference to all the C/C++ functions present in out system, it will be so much easier to write C programs with those functions. I posted this question to our ilugc, they introduced ctags to me.

ctags is a simple utility which will produce a ctags file which contains all definitions of macros, functions, structures, etc., If you want to know more about it, try man ctags.

The ctags otuput file will be used by editors like vi, emacs to help developers to know about the syntex and function definiton.

I thought, It would be good if we can able to grep for functions, macros, from the ctags file. Here is a simple script to achieve this task. Don’t forget to run,

$ ctags --verbose --recurse /usr/include

before executing this script. If you know better way to get reference to functions in our system, kindly share with me.

#!/bin/sh
#
# Description:
# program to search for functions, macros, definiton, etc.,
# in a 'ctags' file.
#
# Author: Mohan Raman
# License: Its in public domain, use it whatever way you want

USAGE="[USAGE]
     ctagsfilter.sh [-n tagname]  [-t tagtype] [-f headerfilename]
             [-h help] ctagsfile1 [ctagsfile2 ...]
"
HELP="${USAGE}
[DESCRIPTION]
     -n tagname              tag name to search
     -f headerfilename       header file to search
     -t tagtype              tag type, anyone of listed below
                             c       class
                             d       defined macro
                             e       enum/enum member
                             f       function
                             g       global
                             m       member of struct/class/enum/union
                             n       namespace
                             s       struct
                             t       typedef
                             u       union
                             v       global variable
     -h                      print this help
"

while getopts "n:t:f:h" OPTIONS
do
     case "${OPTIONS}" in
     n) TAGNAME="${OPTARG}";;
     t) TAGTYPE="${OPTARG}";;
     f) HEADER="${OPTARG}";;
     h) echo "${HELP}" && exit 0;;
     \?) echo "${USAGE}" && exit 1;;
     esac
done

shift $((OPTIND - 1))
test "${#}" -eq 0 && echo "${USAGE}" && exit 1

for FILE
do
     OUTPUTBUFFER=`cat "${FILE}"`

     if test ! -z "${TAGNAME}"
     then
             OUTPUTBUFFER=`echo "${OUTPUTBUFFER}" |
                     awk -F' ' "\\$1 ~ /${TAGNAME}/{print \\$0;}"`
     fi

     if test ! -z "${HEADER}"
     then
             OUTPUTBUFFER=`echo "${OUTPUTBUFFER}" |
                     awk -F' ' "\\$2 ~ /${HEADER}/{print \\$0;}"`
     fi

     if test ! -z "${TAGTYPE}"
     then
             OUTPUTBUFFER=`echo "${OUTPUTBUFFER}" |
                     grep ";\"       ${TAGTYPE}"`
     fi

     echo "${OUTPUTBUFFER}"
done