2

I need a utility to check conflicts in header guards. It would be nice if the utility could check if symbols and file names are consistent (using regex or something).

Regards, rn141.

EDIT:

Example 1. Broken header guard. Doesn't protect from multiple inclusion.

// my_file1.h
#ifndef my_project_my_file1_h__
#define my_project_my_fil1_h__ // should be my_project_my_file1_h__
    // code goes here
#endif

Example 2. Conflicts with the above header guard.

// my_file2.h
#ifndef my_project_my_file1_h__ // should be my_project_my_file2_h__
#define my_project_my_file1_h__ // should be my_project_my_file2_h__
    // code goes here
#endif
user401947
  • 840
  • 10
  • 18
  • 4
    Your header guard names are illegal - you are not allowed to create names that include double underscores - they are reserved for the C++ impleme3ntation. –  Jul 30 '10 at 11:30
  • My system has a utility for dealing with such errors. It's called vi. I have a similar problem when I type `i++` when I really meant `j++`; can you suggest a utility that would check that for me? – msw Jul 30 '10 at 12:12
  • Strangely, those header guards are generated by well known visual studio plugin. The project at hand doesn't use double scores. – user401947 Jul 30 '10 at 12:53

3 Answers3

4

How about using #pragma once instead?

AshleysBrain
  • 20,705
  • 15
  • 81
  • 119
3

I wrote this code in 3 minutes, so it's not perfect:

#!/bin/python
from glob import glob
import re

regex = re.compile(r"#ifndef +([a-zA-z0-9]+)\n *#define +([a-zA-z0-9]+)")

HEADER_EXTENSION = "h"

file_list = glob("*." + HEADER_EXTENSION)
guards_list = []

for file_name in file_list:
    code = None
    with open(file_name) as f:
        code = f.read()
    m = regex.match(code)
    if m:
        group1 = m.group(1)
        group2 = m.group(2)
        if group1 in guards_list:
            print "duplicate %s" % group1
        else:
            guards_list.append(group1)
        if group1 != group2:
            print "guards differents in file %s" % file_name
    else:
        print "can't find guard in %s" % file_name
Ruggero Turra
  • 14,523
  • 14
  • 72
  • 123
0

I'm not aware of any regex or off the shelf utility that can do that kind of analysis easily.

It wouldn't be hard to write your own such program as long as your projects/files adhere to a specific convention for naming the include guards.

Mark B
  • 91,641
  • 10
  • 102
  • 179