【C++】解决C++ “multiple definition of .. first defined here“问题

简介: C++ "multiple definition of .. first defined here" 在C++中,有时候需要在不同文件中使用同一个变量。对于这类变量如果处理不当,很容易出现“multiple definition of... first defined here”的错误。

问题一般出在include上!

例如,定义了如下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 a.cpp b.cpp

提示错误为:

[chris@zz jojo]g++ -o main a.cpp b.cpp
/tmp/ccc7OcsO.o:(.bss+0x0): multiple definition of `b'
/tmp/ccs7q2VA.o:(.bss+0x0):第一次在此定义

出错原因:a.cpp和b.cpp先分别被编译为.o格式的目标文件,两个目标文件再被链接器链接起来,这当中a.cpp和b.cpp分别进行了一次include“global.h”,相当于global.h中的代码重复出现了一次。因为a是const类型,所以重新定义也没事;但是b只是普通变量,重复定义显然不行。

显然,一个解决办法是把b定义为const int类型。或者,定义成static int类型也行。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值