C++ multiple definition problem

Recently I write a reading data interface, and face a problem, which the compiler always say my program has multiple definition of some data variable. Then I try to remove the cpp files from project file list, and put the multiple-definition variables into the header files, at last only include the respect header files, amazing thing happenen! The error disappear! Now I still not find the reason, if anyone know this reason, please tell me,  I will very appreciate it! Besides, I need to mention another solution to this error, which you can place the multiple-definition variable in main.cpp only, that's also can solve this problem.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,multiple definition(多重定义)是指在程序多次定义了同实体(变量、函数、类等这通常会致编译错误,因为编译器无法确定应该使用哪个定义。 多重定义的常见情况包括: 1. 头文件被多次包含:如果一个头文件被多源文件包含,而这些源文件被同时编译,就会导致多重定义。可以通过头文件保护宏(例如 #ifndef)避免这种情况。 2. 全局变量被多次定义:如果在多个源文件中都定义了同名的全局变量,就会导致多重定义。可以将全局变量声明为 extern,然后在一个源文件中进行定义,其他源文件中只需进行声明即可。 3. 函数被多次定义:如果在多个源文件中都定义了同名的函数,就会导致多重定义。可以将函数声明为 inline 或者 static,或者将函数定义放在单独的源文件中,并在其他源文件中进行声明。 解决多重定义问题的方法包括: 1. 使用头文件保护宏:在头文件的开头和结尾使用 #ifndef 和 #endif 来包围内容,确保头文件只被包含一次。 2. 使用 extern 关键字:将全局变量的定义放在一个源文件中,并在其他源文件中使用 extern 进行声明。 3. 使用 inline 或 static 关键字:将函数声明为 inline 或 static,使其在每个源文件中都有自己的副本,避免多重定义。 4. 将函数定义放在单独的源文件中:将函数的实现放在一个源文件中,并在其他源文件中进行声明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值