Search code examples
cincludec-preprocessorconditional-compilation

Counting the number of # includes and # define


I'd like to use C program to find the total number of directives like #include, #define, #ifdef, #typedef, etc. Could you suggest any logic for that? I'm not interested in using any scripting or tools. I want it to be done purely using C program.


Solution

  • Store all the directives in an array of pointers (or arrays).

    Read the C file line by line and check if the first word starts with any of the directives in the list excluding any whitespaces at the beginning.

    char *directives[]={"#assert", "#define#, ......};
    
    int count[NUM_DIRS]= { 0 };
    

    Everytime you find a match increment the correspondin index of the count array. You can also maintain another counter for total to avoid adding values in count array.