【问题标题】:C/C++ Header guard consistencyC/C++ Header 保护一致性
【发布时间】:2010-08-02 02:24:01
【问题描述】:

我需要一个实用程序来检查标头保护中的冲突。如果该实用程序可以检查符号和文件名是否一致(使用正则表达式或其他东西),那就太好了。

问候, rn141。

编辑:

示例 1. 损坏的头球后卫。不能防止多重包含。

// 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

示例 2. 与上述 header 保护冲突。

// 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

【问题讨论】:

  • 您的标头保护名称是非法的 - 您不能创建包含双下划线的名称 - 它们是为 C++ 实现保留的。
  • 我的系统有一个用于处理此类错误的实用程序。它被称为 vi。当我真正的意思是j++ 时,我在输入i++ 时遇到了类似的问题;你能推荐一个可以帮我检查的实用程序吗?
  • 奇怪的是,这些标题保护是由著名的 Visual Studio 插件生成的。手头的项目不使用双倍分数。

标签: c++ c


【解决方案1】:

改用#pragma once 怎么样?

【讨论】:

  • 并非所有编译器都支持#pragma once
【解决方案2】:

这段代码我用了 3 分钟写出来,所以并不完美:

#!/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

【讨论】:

    【解决方案3】:

    我不知道有任何正则表达式或现成的实用程序可以轻松进行这种分析。

    只要您的项目/文件遵守命名包含保护的特定约定,编写您自己的此类程序并不难。

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 1970-01-01
      • 2011-05-30
      • 2011-06-13
      • 2021-04-14
      • 2011-06-01
      • 1970-01-01
      • 2012-09-09
      • 2018-11-01
      相关资源
      最近更新 更多