开发者

C/C++ Header guard consistency

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 m开发者_开发百科y_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


How about using #pragma once instead?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜