问题解决:只定义了一次函数,为什么会报错重复定义?

目录

问题发现

解决方法

 (一)删除主函数里的引用

(二)封装文件头


问题发现

今天在敲代码的时候,发现明明在一个头文件里定义了一次函数,运行代码时却总是报错重复定义的函数如

In file included from search_and_order.h:5,
from main1.cpp:5:
printOriginal.h:5:6: error: redefinition of 'void printOriginal_(MYSQL)'
void printOriginal_(MYSQL my_sql_original)

 经调查发现,原来在头文件1里包含头文件2,并且主函数包含了tou'we会导致重复定义的问题

来看个例子

/* test.cpp */
#include<iostream>
#include"test1.h"
#include"test2.h"

int main()
{
    print_hallo_welt_2();
}
/* test1.h */
#include<iostream>

void print_hallo_welt()
{
    std::cout << "Hello, hallo_welt" << std::endl;
}
/* test2.h */
#include<iostream>
#include"test1.h"

void print_hallo_welt_2()
{
    print_hallo_welt();
}

运行test.cpp时 出现了重复调用的问题

解决方法

 (一)删除主函数里的引用

/* test.cpp */
#include<iostream>
//#include"test1.h"
#include"test2.h"

int main()
{
    print_hallo_welt_2();
}

成功输出 

Hello, hallo_welt

(二)封装文件头

封装文件头是将头文件的所有代码放在头文件守卫内部,以确保头文件只被包含一次,并防止重复定义和编译错误,如

#ifndef PRINTORIGINAL_H
#define PRINTORIGINAL_H

#include<iostream>
#include<mysql.h>
// 其他需要包含的头文件

// 这里放置头文件中的所有代码,如函数声明、类定义等

#endif // PRINTORIGINAL_H

封!

(不同的头文件要使用不同的宏来封装) (就是#ifndef后面的,可以自己命名)

/* test1.h */

#ifndef TEST1_H
#define TEST1_H

#include<iostream>

void print_hallo_welt()
{
    std::cout << "Hello, hallo_welt" << std::endl;
}

#endif
/* test2.h */

#ifndef PRINTORIGINAL_H
#define PRINTORIGINAL_H

#include"test1.h"
#include<iostream>

void print_hallo_welt_2()
{
    print_hallo_welt();
}


#endif

运行成功 

Hello, hallo_welt

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hhhalloWelt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值