代码之家  ›  专栏  ›  技术社区  ›  kmalmur

C头文件和源文件的标准结构

  •  0
  • kmalmur  · 技术社区  · 15 年前

    C源文件和头文件是否有标准化的结构?

    我在考虑这样的事情(例如C源文件):

    //静态变量

    //静态方法

    //公共方法

    4 回复  |  直到 15 年前
        1
  •  1
  •   JeremyP    15 年前

    这是一个完全主观的问题。不过,我大致是这样做的。

    标题:

    // extern defines, constants and enums
    // public types
    // extern methods
    

    没有外部变量:-)

    编制单位:

    // includes
    // definitions for extern constants
    // static function prototypes
    // everything else
    

        2
  •  1
  •   stinky472    15 年前

    // static variables
    // public variables
    // static methods
    // public methods
    

    // static variables
    // public variables (external linkage)
    // static functions
    // public functions
    

    重要的是保持一致性,我建议避免任何非常奇怪的东西,因为它会吓跑其他必须查看代码的开发人员。如果你想和其他工程师一起工作,异国风格通常是不好的。越是异国情调的风格,他们就越是独特的个人风格,他们就越需要别人根据个人喜好来调整。

    一定要尽量减少有外部联系的公共变量(全局变量)的数量。尽管差别听起来很小,但编写一个公共函数来获取一个变量是一个很大的进步,即使它是一个简单的getter类型函数,返回一个指向该变量的指针,因为它至少允许您在需要更改时修改代码,还允许您轻松地将断点放在访问它的任何地方,在函数中添加指令插入等。

        3
  •  1
  •   Nick Van Brunt    15 年前

    对于c,我通常使用以下方法:

    // include guard
    #ifndef <filename>_H
    #define <filename>_H
    
    // define this as extern for c++
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    #include <libraries>
    #define  <preproc variables>
    #define  <preproc macros>
    
    enum <enums> {
    };
    
    typedef <variables>;
    typedef <structs>;
    
    function prototypes();
    
    // end c++ guard
    #ifdef __cplusplus
    }
    #endif 
    // end include guard
    #endif
    
        4
  •  0
  •   Ramakrishna    15 年前

    你使用的结构很好。