Search code examples
c++grepinclude-guardsgnu-coreutils

Find include guard typos in C++ with gnu coreutils


Below is a typo for a C++ include guard. Both should read _MYFILE_H_.

#ifndef _MYFILE_H_
#define _MYFLIE_H_

How would you suggest searching a bunch of header files for a typo like this using GNU coreutils (e.g. grep, awk)?


Solution

  • You could use awk:

    {
      if ($1 == "#ifndef") { was_ifdef = 1; def = $2 }
      else if ($1 == "#define" && was_ifdef) 
        { 
          if ($2 != def)   printf("Mismatch in %s: expected %s found %s\n", FILENAME, def, $2);
        }
      else was_ifdef = 0;
    }
    

    There may be more clever ways to do this, but this is (to me) quite clear and easy.

    Note: This will show "false positives" if the file contains something like

    #ifndef FOO_DEFINED
    typedef int foo;
    #define FOO_DEFINED 
    #endif