C++ "multiple definition of .. first defined here"

本文探讨了C++中头文件引用时可能导致的多定义错误,并提供了两个解决方案:一是确保常量的正确定义,二是使用静态变量以允许在不同文件中修改变量。通过实例演示了如何避免此类常见编程问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在C++中,经常需要include一些自己定义的头文件,如果处理不当,很容易出现"multipe definition ....."的错误。

闲话少说,先来一个例子:

假设定义了如下3个文件:global.h  a.cpp b.cpp

//global.h:

#ifndef _GLOBAL_H_

#define _GLOBAL_H_

const int a=1;

int b;

#endif
//a.cpp
#include <iostream> #include <stdlib.h> #include "global.h" using namespace std; void test1() { cout<<"test1"<<endl; }
//b.cpp
#include <iostream> #include <stdlib.h> #include "global.h" using namespace std; void test2() { cout<<"test2"<<endl; }

void main()
{
cout<<"hello world"<<endl;
}

编译:g++ -o main test1.cpp test2.cpp

提示出现错误:multiple definition of b....

解决方法:

1. 要是b是一个常量的话,就直接定义成const int b;即可

2. 将b定义成static, 这样在include “global.h” 的cpp中都能修改b

转载于:https://www.cnblogs.com/denflyson/archive/2012/07/13/2590440.html

gcc main.o ListManage.o -o list ListManage.o: In function `screen': ListManage.c:(.text+0x0): multiple definition of `screen' main.o:main.c:(.text+0x0): first defined here ListManage.o: In function `creatNode': ListManage.c:(.text+0x5b): multiple definition of `creatNode' main.o:main.c:(.text+0x5b): first defined here ListManage.o: In function `listPrint': ListManage.c:(.text+0xd1): multiple definition of `listPrint' main.o:main.c:(.text+0xd8): first defined here ListManage.o: In function `listPushBack': ListManage.c:(.text+0x198): multiple definition of `listPushBack' main.o:main.c:(.text+0x156): first defined here ListManage.o: In function `listDelete': ListManage.c:(.text+0x22f): multiple definition of `listDelete' main.o:main.c:(.text+0x1e4): first defined here ListManage.o: In function `listNameFind': ListManage.c:(.text+0x2f8): multiple definition of `listNameFind' main.o:main.c:(.text+0x2ad): first defined here ListManage.o: In function `listIDFind': ListManage.c:(.text+0x349): multiple definition of `listIDFind' main.o:main.c:(.text+0x2fe): first defined here ListManage.o: In function `listDestory': ListManage.c:(.text+0x38d): multiple definition of `listDestory' main.o:main.c:(.text+0x342): first defined here ListManage.o: In function `userInput': ListManage.c:(.text+0x3e4): multiple definition of `userInput' main.o:main.c:(.text+0x399): first defined here collect2: error: ld returned 1 exit status makefile:10: recipe for target 'list' failed make: *** [list] Error 1
最新发布
08-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值