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

posted @ 2012-07-13 16:12  菜鸟的世界  阅读(16725)  评论(0编辑  收藏  举报