利用预编译解决C/C++重复定义的错误 -2020.09.13

利用预编译解决C/C++重复定义的错误 -2020.09.13

我们现在有main.c和function.h两个文件

main.c

#include <stdio.h>

#include "function.h"

int main() {
    printf("Hello, World!\n");
    printf("\t1+2+...+100\n"sum(100));
    return 0;
}

int sum(int n) {
    int res = 0;
    for (int i = 0; i < n; ++i) {
        res += i;
    }
    return res;
}

function.h

//#ifndef __SUM_H
//#define __SUM_H

int sum(int n);
int A = 0;

//#endif

我们使用命令gcc main.c -o hello,再使用ls,可以看到当前目录下已经生成了hello.exe

然后我们再使用命令.\hello.exe运行程序,.\表示当前目录

到目前为止都没什么不对的地方,现在我们添加一个function2.h,并在main.c中引入function2.h

function2.h的内容如下

#include "function.h"

main.c引入部分修改为

#include <stdio.h>

#include "function.h"
#include "function2.h"

我们再次使用命令gcc main.c -o hello,发现出现了报错信息redefinition

意思就是重复定义了变量A,那么我们需要在function.h中加入预编译指令#ifndef #define #endif,

这样可以有效防止重复定义或者重复包含的问题,我们将function.h中的三条预编译指令解注释

function.h修改为

#ifndef __SUM_H
#define __SUM_H

int sum(int n);
int A = 0;

#endif

我们再次使用命令gcc main.c -o hello,发现编译正确通过了,再次运行程序

结果正确,因此在规范的开发当中我们需要使用#ifndef #define #endif来防止重复定义的问题