利用预编译解决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来防止重复定义的问题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值