推荐的C编程风格(干货)

1. 推荐的C编程风格

本文档是根据Tilen MAJERLE的推荐的C编程规则整理而来。添加配合Doxygen相关的注释,可实现生成注释文档。纯干货,整理出来内容挺多的,建议收藏慢慢看。

2. 通用规则

这里列出来一些必要并重要的通用规则

  • 使用c99标准
  • 使用空格,尽量别使用制表符
  • 使用4个空格代表一个缩进
  • 在功能名称和左括号之间尽量别使用空格
int a = sum(4, 3);      /* OK */
int a = sum (4, 3);     /* Wrong */
  • 打开花括号始终与关键字位于同一行(forwhiledoswitchif,…)
int a;
for (a = 0; a < 5; i++) {           /* OK */
}
for (a = 0; a < 5; i++){            /* Wrong */
}
for (a = 0; a < 5; i++)             /* Wrong */
{
}
  • 在比较和赋值运算符之前和之后使用单个空格
int a;
a = 3 + 4;              /* OK */
for (a = 0; a < 5; a++) /* OK */
a=3+4;                  /* Wrong */
a = 3+4;                /* Wrong */
for (a=0;a<5;a++)       /* Wrong */
  • 每个逗号后使用单个空格
func_name(5, 4);        /* OK */
func_name(4,3);         /* Wrong */
  • 尽量让编译器初始化staticglobal变量初始化为0(或NULL)
static int a;           /* OK */
static int b = 4;       /* OK */
static int a = 0;       /* Wrong */

void
my_func(void) {
    static int* ptr;    /* OK */
    static char abc = 0;/* Wrong */
}
  • 在同一行中声明相同类型的所有局部变量
void
my_func(void) {
    char a;             /* OK */
    char a, b;          /* OK */
    char b;             /* Wrong, variable with char type already exists */
}
  • for循环中声明计数器变量
/* OK */
for (int i = 0; i < 10; i++)

/* OK, if you need counter variable later */
int i;
for (i = 0; i < 10; i++) {
    if (...) {
        break;
    }
}
if (i == 10) {

}

/* Wrong */
int i;
for (i = 0; i < 10; i++) ...
  • 避免使用声明中的函数调用进行变量赋值,单变量除外
void
a(void) {
    /* Avoid function calls when declaring variable */
    int a, b = sum(1, 2);
    
    /* Use this */
    int a, b;
    b = sum(1, 2);

    /* This is ok */
    uint8_t a = 3, b = 4;
}
  • 除了charfloat或者double总是使用stdint.h库中声明的类型,例如。uint8_tunsigned 8-bit
  • 不要使用stdbool.h库。分别使用10表示truefalse
/* OK */
uint8_t status;
status = 0;

/* Wrong */
#include "stdbool.h"
bool status = true;

  • 永远不要与true比较,例如。 if(check_func()== 1),使用if(check_func()){...}
  • 总是将指针与NULL值进行比较
/* OK, compare against NULL */
uint8_t* ptr;
if (ptr == NULL || ptr != NULL) {

}

/* Wrong */
if (ptr || !ptr) {

}

  • 始终对长度或大小变量使用size_t
  • 如果函数不修改pointer指向的内存,则始终使用const作为指针
  • 当函数可以接受任何类型的指针时,总是使用void *,不要使用uint8_t *
    • 功能必须在实施中注意正确的铸造
/*
 * To send data, function should not modify memory pointed to by `data` variable
 * thus `const` keyword is important
 *
 * To send generic data (or to write them to file)
 * any type may be passed for data,
 * thus use `void *`
 */
/* OK example */
void
send_data(const void* data, size_t len) { /* OK */
    /* Do not cast `void *` or `const void *` */
    const uint8_t* d = data;/* Function handles proper type for internal usage */
}

  • 切勿使用可变长度数组(VLA)。 使用动态内存分配代替标准Cmallocfree函数,或者如果库/项目提供自定义内存分配,请使用其实现
  • 始终使用带有sizeof运算符的括号。
/* OK */
#include "stdlib.h"
void my_func(size_t size) {
    int* arr;
    arr = malloc(sizeof(*arr) * n); /* OK, Allocate memory */
    arr = malloc(sizeof *arr * n);  /* Wrong, brackets for sizeof operator are missing */
    if (arr == NULL) {
        /* FAIL, no memory */
    }
    
    free(arr);  /* Free memory after usage */
}

/* Wrong */
void
my_func(int size) {
    int arr[size];      /* Wrong, do not use VLA */
}

  • 总是使用/ * comment * /作为评论,即使是单行评论
  • 始终在头文件中包含检查C ++extern关键字
  • 即使函数是静态,每个函数都必须包含doxygen-enabled comment
  • 对函数,变量,注释使用英文名称/文本
  • 永远不要将函数返回void *,例如。 uint8_t * ptr =(uint8_t *)func_returning_void_ptr();asvoid *被安全地提升为任何其他指针类型
  • 当转换为指针类型时,总是在类型和星号之间添加空格,例如。 uint8_t * t =(uint8_t *)var_width_diff_type
  • 始终遵守项目或库中已使用的代码样式

3. 注释

  • 始终使用/ * comment * /代替以//开头的注释。 即使对于单行注释也是如此
//This is comment (wrong)
/* This is comment (ok) */

  • 对于多行注释,每行使用space + asterix
/*
 * This is multi-line comments,
 * written in 2 lines (ok)
 */
 
/**
 * Wrong, use double-asterix only for doxygen documentation
 */
 
/*
* Single line comment without space before asterix (wrong)
*/

/*
 * Single line comment in multi-line configuration (wrong)
 */

/* Single line comment (ok) */

  • 在注释时使用12缩进(12 * 4空格)偏移。 如果语句大于12缩进,则将注释4-spaces对齐(下面的示例)
void
my_func(void) {
    char a, b;
                                                
    a = call_func_returning_char_a(a);				/* This is comment with 12*4 spaces indent from beginning of line */
    b = call_func_returning_char_a_but_func_name_is_very_long(a);   /* This is comment, aligned to 4-spaces indent */
}

4. 函数

  • 可以从外部模块访问的每个函数,必须包含函数原型或者使用声明

  • 函数名必须为小写,可选地用下划线_字符分隔

/* OK */
void my_func(void);
void myfunc(void);

/* Wrong */
void MYFunc(void);
void myFunc();

  • 当函数返回指针时,在星号和数据类型之间添加空格
/* OK */
const char * my_func(void);
my_struct_t * my_func(int a, int b);

/* Wrong */
const char *my_func(void);
my_struct_t* my_func(void);

  • 对齐所有具有相同/相似的功能函数原型以提高可读性
/* OK, function names aligned */
void        set(int a);
my_type_t   get(void);
my_ptr_t *  get_ptr(void);

/* Wrong */
void set(int a);
const char* get(void);

  • 函数实现必须包含单独行中的返回类型和可选的其他关键字
/* OK */
int
foo(void) {
    return 0;
}

/* OK */
static const char *
get_string(void) {
    return "Hello world!\r\n";
}

/* Wrong */
int foo(void) {
    return 0;
}

  • 当函数返回指针时,星号字符必须在类型和字符之间添加空格(char *
/* OK */
const char *
foo(void) {
    return "test";
}

/* Wrong */
const char*
foo(void) {
    return "test";
}

5. 变量

  • 使用可选的下划线_字符使变量名全部小写
/* OK */
int a;
int my_var;
int myvar;

/* Wrong */
int A; 
int myVar;
int MYVar;

  • 通过type将局部变量组合在一起
void
foo(void) {
    int a, b;   /* OK */
    char a;
    char b;     /* Wrong, char type already exists */
}

  • 在第一个可执行语句之后不要声明变量
void
foo(void) {
    int a;
    a = bar();
    int b;      /* Wrong, there is already executable statement */
}

  • 在下一个缩进级别中声明新变量
int a, b;
a = foo();
if (a) {
    int c, d;   /* OK, c and d are in if-statement scope */
    c = foo();
    int e;      /* Wrong, there was already executable statement inside block */
}

  • 声明指针变量,并将星号与类型对齐
/* OK */
char* a;

/* Wrong */
char *a;
char * a;

  • 声明多个指针变量时,可以使用与变量名对齐的星号声明它们
/* OK */
char *p, *n;

6. 结构体、枚举类、类型定义

  • 结构或枚举名称必须小写,并且单词之间带有可选的下划线_字符
  • 结构或枚举可能包含typedef关键字
  • 所有结构成员必须为小写
  • 所有枚举成员必须为大写
  • 声明每个成员在自己的行中,即使它们共享相同的类型,例如: 尽量别int a,b
  • 结构/枚举必须遵循doxygen文档语法

声明结构时,它可以使用下面其中一种:

  1. 当结构仅使用名称声明时,它的名称后面不能包含_t后缀。
struct struct_name {
    char* a;
    char b;
};

  1. 当结构仅使用typedef声明时,它的名称后面必须包含_t后缀。
typedef struct {
    char* a;
    char b;
} struct_name_t;

  1. 当使用name和typedef声明结构时,它必须不包含基本名称的_t,并且在其typedef部分的名称后必须包含_t后缀。
typedef struct struct_name {
    char* a;
    char b;
    char c;
} struct_name_t;

不好的声明示例及其更正建议

/* a and b must be separated to 2 lines */
/* Name of structure with typedef must include _t suffix */
typedef struct {
    int a, b;
} a;

/* Corrected version */
typedef struct {
    int a;
    int b;
} a_t;

/* Wrong name, it must not include _t suffix */
struct name_t {
    int a;
    int b;
};

/* Wrong parameters, must be all uppercase */
typedef enum {
    MY_ENUM_TESTA,
    my_enum_testb,
} my_enum_t;

  • 在声明时初始化结构时,使用C99初始化样式
/* OK */
a_t a = {
    .a = 4,
    .b = 5,
};

/* Wrong */
a_t a = {1, 2};

  • 当函数句柄引入新的typedef时,请使用_fn后缀
/* Function accepts 2 parameters and returns uint8_t */
/* Name of typedef has `_fn` suffix */
typedef uint8_t (*my_func_typedef_fn)(uint8_t p1, const char* p2);

7. 复合语句

  • 每个复合语句必须包括开括号和右括号,即使它只包含1嵌套语句
  • 每个复合声明必须包括单个缩进; 嵌套语句时,每个嵌套包含1缩进大小
/* OK */
if (c) {
    do_a();
} else {
    do_b();
}

/* Wrong */
if (c)
    do_a();
else
    do_b();
    
/* Wrong */
if (c) do_a();
else do_b();

  • 如果是ifif-else-if语句,else必须与第一个语句的结束括号在同一行
/* OK */
if (a) {

} else if (b) {

} else {

}

/* Wrong */
if (a) {

} 
else {

}

/* Wrong */
if (a) {

} 
else
{

}

  • do-while语句的情况下,while部分必须与do部分的右括号在同一行
/* OK */
do {
    int a;
    a = do_a();
    do_b(a);
} while (check());

/* Wrong */
do
{
/* ... */
} while (check());

/* Wrong */
do {
/* ... */
}
while (check());

  • 每个开头都需要缩进
if (a) {
    do_a();
} else {
    do_b();
    if (c) {
        do_c();
    }
}

  • 即使是单个语句,也不要在没有大括号的情况下执行复合语句。 以下示例显示了不良做法
if (a) do_b();
else do_c();

if (a) do_a(); else do_b();

  • whiledo-whilefor循环必须包括括号
/* OK */
while (is_register_bit_set()) {}

/* Wrong */
while (is_register_bit_set());
while (is_register_bit_set()) { }
while (is_register_bit_set()) {
}

  • while(或fordo-while等)为空(在嵌入式编程中可能就是这种情况),请使用空的单行括号
/* Wait for bit to be set in embedded hardware unit
uint32_t* addr = HW_PERIPH_REGISTER_ADDR;

/* Wait bit 13 to be ready */
while (*addr & (1 << 13)) {}        /* OK, empty loop contains no spaces inside curly brackets */
while (*addr & (1 << 13)) { }       /* Wrong */
while (*addr & (1 << 13)) {         /* Wrong */

}
while (*addr & (1 << 13));          /* Wrong, curly brackets are missing. Can lead to compiler warnings or unintentional bugs */

8. 选择语句

  • 为每个case语句添加单个缩进
  • 在每个casedefault中为break语句使用额外的单个缩进
/* OK, every case has single indent */
/* OK, every break has additional indent */
switch (check()) {
    case 0:
        do_a();
        break;
    case 1:
        do_b();
        break;
    default:
        break;
}

/* Wrong, case indent missing */
switch (check()) {
case 0:
    do_a();
    break;
case 1:
    do_b();
    break;
default:
    break;
}

/* Wrong */
switch (check()) {
    case 0:
        do_a();
    break;      /* Wrong, break must have indent as it is under case */
    case 1:
    do_b();     /* Wrong, indent under case is missing */
    break;
    default:
        break;
}

  • 始终包含default语句
/* OK */
switch (var) {
    case 0: 
        do_job(); 
        break;
    default: break;
}

/* Wrong, default is missing */
switch (var) {
    case 0: 
        do_job(); 
        break;
}

  • 如果需要局部变量,请使用大括号并在其中放入break语句。
    • 将开口花括号放在与case语句相同的行中
switch (a) {
    /* OK */
    case 0: {
        int a, b;
        char c;
        a = 5;
        /* ... */
        break;
    }
    
    /* Wrong */
    case 1:
    {
        int a;
        break;    
    }
    
    /* Wrong */
    case 2: {
        int a;   
    }
    break; 
}

9. 宏和预处理器指令

  • 始终使用宏而不是文字常量,特别是数字
  • 所有宏必须是完全大写的,带有可选的下划线_字符,除非它们被明确标记为函数,将来可能会替换为常规函数语法
/* OK */
#define MY_MACRO(x)         ((x) * (x))

/* Wrong */
#define square(x)           ((x) * (x))

  • 始终用括号保护输入参数
/* OK */
#define MIN(x, y)           ((x) < (y) ? (x) : (y))

/* Wrong */
#define MIN(x, y)           x < y ? x : y

  • 始终用括号保护最终的宏观评估
/* Wrong */
#define MIN(x, y)           (x) < (y) ? (x) : (y)
#define SUM(x, y)           (x) + (y)

/* Imagine result of this equation using wrong SUM implementation */
int x = 5 * SUM(3, 4);      /* Expected result is 5 * 7 = 35 */
int x = 5 * (3) + (4);      /* It is evaluated to this, final result = 19 which is not what we expect */

/* Correct implementation */
#define MIN(x, y)           ((x) < (y) ? (x) : (y))
#define SUM(x, y)           ((x) + (y))

  • 当宏使用多个语句时,使用do-while(0)语句保护它
typedef struct {
    int px, py;
} point_t;
point_t p;                  /* Create new point */

/* Wrong implementation */

/* Define macro to set point */
#define SET_POINT(p, x, y)  (p)->px = (x); (p)->py = (y)    /* 2 statements. Last one should not implement semicolon */

SET_POINT(&p, 3, 4);        /* Set point to position 3, 4. This evaluates to... */
(&p)->px = (3); (&p)->py = (4); /* ... to this. In this example it is not a problem. */

/* Consider this ugly code, however it is valid by C standard (not recommended) */
if (a)                      /* If a is true */
    if (b)                  /* If b is true */
        SET_POINT(&p, 3, 4);/* Set point to x = 3, y = 4 */
    else
        SET_POINT(&p, 5, 6);/* Set point to x = 5, y = 6 */

/* Evaluates to code below. Do you see the problem? */
if (a)
    if (b) 
        (&p)->px = (3); (&p)->py = (4);
    else
        (&p)->px = (5); (&p)->py = (6);

/* Or if we rewrite it a little */
if (a)
    if (b) 
        (&p)->px = (3);
        (&p)->py = (4);
    else
        (&p)->px = (5);
        (&p)->py = (6);

/*
 * Ask yourself a question: To which `if` statement `else` keyword belongs?
 *
 * Based on first part of code, answer is straight-forward. To inner `if` statement when we check `b` condition
 * Actual answer: Compilation error as `else` belongs nowhere
 */

/* Better and correct implementation of macro */
#define SET_POINT(p, x, y)  do { (p)->px = (x); (p)->py = (y); } while (0)    /* 2 statements. No semicolon after while loop */
/* Or even better */
#define SET_POINT(p, x, y)  do {    \   /* Backslash indicates statement continues in new line */
    (p)->px = (x);                  \
    (p)->py = (y);                  \
} while (0)                             /* 2 statements. No semicolon after while loop */

/* Now original code evaluates to */
if (a)
    if (b) 
        do { (&p)->px = (3); (&p)->py = (4); } while (0);
    else
        do { (&p)->px = (5); (&p)->py = (6); } while (0);

/* Every part of `if` or `else` contains only `1` inner statement (do-while), thus we have valid evaluation */

/* To make code perfect, use brackets for every if-ifelse-else statements */
if (a) {                    /* If a is true */
    if (b) {                /* If b is true */
        SET_POINT(&p, 3, 4);/* Set point to x = 3, y = 4 */
    } else {
        SET_POINT(&p, 5, 6);/* Set point to x = 5, y = 6 */
    }
}

  • 始终使用额外的hideinitializer doxygen关键字将宏文档编写为常规函数
#define MY_MACRO(x)         ((x) * 2)

  • 避免使用#ifdef#ifndef。 请改用defined()!defined()
#ifdef XYZ
/* do something */
#endif /* XYZ */

  • 始终记录if / elif / else / endif语句
/* OK */
#if defined(XYZ)
/* Do if XYZ defined */
#else /* defined(XYZ) */
/* Do if XYZ not defined */
#endif /* !defined(XYZ) */

/* Wrong */
#if defined(XYZ)
/* Do if XYZ defined */
#else
/* Do if XYZ not defined */
#endif

  • 不要在#if语句中缩进子语句
/* OK */
#if defined(XYZ)
#if defined(ABC)
/* do when ABC defined */
#endif /* defined(ABC) */
#else /* defined(XYZ) */
/* Do when XYZ not defined */
#endif /* !defined(XYZ) */

/* Wrong */
#if defined(XYZ)
    #if defined(ABC)
        /* do when ABC defined */
    #endif /* defined(ABC) */
#else /* defined(XYZ) */
    /* Do when XYZ not defined */
#endif /* !defined(XYZ) */

10. 说明文档

记录的代码允许doxygen解析和一般的html / pdf / latex输出,因此正确地执行它是非常重要的。

  • 添加variablesfunctionsstructures / enumerations可识别的doxygen文档样式
  • 总是使用\表示doxygen,不要使用@
  • 始终使用从文本行开头偏移的5x4空格(5个Tab)
/**
 * \brief           Holds pointer to first entry in linked list
 *                  Beginning of this text is 5 tabs (20 spaces) from beginning of line
 */
static
type_t* list;

  • 每个结构/枚举成员必须包含文档
  • 使用12x4空格偏移量开始注释
/**
 * \brief           This is point struct
 * \note            This structure is used to calculate all point 
 *                      related stuff
 */
typedef struct {
    int x;                                      /*!< Point X coordinate */
    int y;                                      /*!< Point Y coordinate */
    int size;                                   /*!< Point size.
                                                    Since comment is very big,
                                                    you may go to next line */
} point_t;

/**
 * \brief           Point color enumeration
 */
typedef enum {
    COLOR_RED,                                  /*!< Red color. This comment has 12x4
                                                    spaces offset from beginning of line */
    COLOR_GREEN,                                /*!< Green color */
    COLOR_BLUE,                                 /*!< Blue color */
} point_color_t;

  • 函数文档必须写在函数实现中(通常是源文件)
  • 功能必须包括brief和所有参数文档
  • 如果分别为 inputoutput分别为inout,则必须注明每个参数
  • 如果函数返回某些内容,则必须包含return参数。 这不适用于void函数
  • 函数可以包含其他doxygen关键字,例如notewarning
  • 在参数名称及其描述之间使用冒号
/**
 * \brief           Sum `2` numbers
 * \param[in]       a: First number
 * \param[in]       b: Second number
 * \return          Sum of input values
 */
int
sum(int a, int b) {
    return a + b;
}

/**
 * \brief           Sum `2` numbers and write it to pointer
 * \note            This function does not return value, it stores it to pointer instead
 * \param[in]       a: First number
 * \param[in]       b: Second number
 * \param[out]      result: Output variable used to save result
 */
void
void_sum(int a, int b, int* result) {
    *result = a + b;
}

  • 如果函数返回枚举成员,请使用ref关键字指定哪一个
/**
 * \brief           My enumeration
 */
typedef enum {
    MY_ERR,                                     /*!< Error value */
    MY_OK                                       /*!< OK value */
} my_enum_t;

/**
 * \brief           Check some value
 * \return          \ref MY_OK on success, member of \ref my_enum_t otherwise
 */
my_enum_t
check_value(void) {
    return MY_OK;
}

  • 使用符号(`NULL `=>NULL)表示常量或数字
/**
 * \brief           Get data from input array
 * \param[in]       in: Input data
 * \return          Pointer to output data on success, `NULL` otherwise
 */
const void *
get_data(const void* in) {
    return in;
}

  • 宏的文档必须包含hideinitializer doxygen命令
/**
 * \brief           Get minimal value between `x` and `y`
 * \param[in]       x: First value
 * \param[in]       y: Second value
 * \return          Minimal value between `x` and `y`
 * \hideinitializer
 */
#define MIN(x, y)       ((x) < (y) ? (x) : (y))

11. 示例

标头和源的模板文件包含在存储库中。
请在下面查看一些文件说明

  • 在文件末尾留下单个空行
  • 每个文件必须包含filebrief描述的doxygen注释,后跟空行
/**
 * \file            template.h
 * \brief           Template include file
 */
                    /* Here is empty line */

  • 每个文件(* header source *)必须包含许可证(打开注释包括单个星号,因为doxygen必须忽略它)
  • 使用项目/库已使用的相同许可证
/**
 * \file            template.h
 * \brief           Template include file
 */

/*
 * Copyright (c) 2018 FirstName LastName
 *  
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * This file is part of library_name.
 *
 * Author:          Author Name <optional_email@example.com>
 */

  • 头文件必须包含警卫#ifndef
  • 头文件必须包含C ++判断
/* License comes here */
#ifndef __TEMPLATE_H
#define __TEMPLATE_H

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* File content here */

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __TEMPLATE_H */

12. 示例文件

.c源文件示例

/**
 * \file            template.c
 * \brief           Template source file
 */

/*
 * Copyright (c) 2018 Tilen Majerle
 *  
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * This file is part of my_library.
 *
 * Author:          Tilen MAJERLE <tilen@majerle.eu>
 */
#include "template.h"

/**
 * \brief			Sum `2` numbers
 * \param[in]		a: First value
 * \param[in]		b: Second value
 * \return			Sum of input values
 */
int
sum(int a, int b) {
	return a + b;
}


.h示例文件

/**
 * \file            template.h
 * \brief           Template header file
 */

/*
 * Copyright (c) 2018 Tilen Majerle
 *  
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * This file is part of my_library.
 *
 * Author:          Tilen MAJERLE <tilen@majerle.eu>
 */
#ifndef __TEMPLATE_H
#define __TEMPLATE_H

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* Function prototypes, name aligned, lowercase names */
int	sum(int a, int b);
int divide(int a, int b);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __TEMPLATE_H */


  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面我会详细讲解一下C语言编程的步骤,希望对您有所帮助。 1. 定义问题 定义问题是编写程序的第一步,也是最重要的一步。在这一步中,需要明确程序的目标和要解决的问题。具体来说,需要回答以下问题: - 你的程序要实现什么功能? - 你的程序要处理什么类型的数据? - 你的程序需要输入什么数据? - 你的程序需要输出什么数据? 定义问题的过程中,需要尽可能详细地描述程序的目标和要解决的问题。这样有助于后续步骤的顺利进行。 2. 设计算法 设计算法是编写程序的核心步骤。在这一步中,需要根据问题的需求,设计程序的算法,选择合适的数据结构和算法策略。具体来说,需要完成以下工作: - 确定程序的输入和输出。 - 根据数据的类型和大小,选择合适的数据结构。 - 设计程序的逻辑流程,包括条件判断、循环结构等。 - 确定算法的复杂度,评估程序的性能。 在这一步中,需要注意算法的正确性和可读性。算法应该能够正确地解决问题,并且易于理解和维护。 3. 编写程序 在完成算法设计后,就可以开始编写程序了。具体来说,需要完成以下工作: - 编写程序的源代码,按照算法设计的逻辑结构组织代码。 - 使用C语言的语法规则,定义变量、函数等。 - 使用控制语句和函数库,实现程序的功能。 在编写程序的过程中,需要注意代码的风格和可读性。代码应该具有良好的组织结构和注释,易于理解和维护。 4. 编译程序 编写程序后,需要使用编译器将程序源代码转换成可执行程序。具体来说,需要完成以下工作: - 使用编译器将程序源代码编译成二进制文件。 - 编译过程中,需要检查代码是否符合C语言的语法规则,是否存在错误。 编译后,会生成可执行文件。可以通过运行可执行文件,测试程序的功能是否正常。 5. 调试程序 运行程序并检查程序是否按照预期工作。如果出现错误,需要进行调试。具体来说,需要完成以下工作: - 分析程序的错误,确定出错的原因。 - 修改代码,消除错误。 - 重新编译程序,测试修改后的程序是否正常工作。 在调试程序的过程中,需要使用调试工具和技术,如断点调试、输出调试等。 6. 优化程序 根据程序的性能需求,对程序进行优化。具体来说,需要完成以下工作: - 分析程序的性能瓶颈,确定需要优化的部分。 - 使用合适的算法和数据结构,减少程序的运行时间和空间复杂度。 - 对代码进行改进,优化程序的可读性和可维护性。 在优化程序的过程中,需要注意程序的正确性和可读性。优化应该是有针对性的,避免过度优化导致新的问题。 7. 维护程序 对程序进行维护,修复已知的错误或更新程序以适应新的需求。具体来说,需要完成以下工作: - 定期检查程序,修复已知的错误。 - 根据新的需求,对程序进行改进和扩展。 在维护程序的过程中,需要注意程序的兼容性和可维护性。维护应该是持续性的,避免放任程序出现新的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值