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


在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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM