错误:多重定义 和 xxx变量已经在xxx.obj中定义
当在一个.cpp文件中定义了一个全局变量之后,需要在其他文件中使用时,需要用到关键字extern
当使用extern修饰一个变量时,例如extern int x; 代表当前变量x 的定义来自于其他文件,当进行编译时,会去其他文件里面找,
在当前文件仅做声明,而不是重新定义一个新的变量
main.cpp
#include <iostream> #include "Some.h" using namespace std; extern int xx123; int main() { Some * some = new Some; some->prntf(); xx123 = 50; cout << "main:" << xx123 << endl;; delete some; system("PAUSE"); return 0; }
Some.h
#ifndef SOME_H #define SOME_H class Some { public: Some(); ~Some(); void prntf(); }; #endif // !SOME_H
Some.cpp
#include "Some.h" #include <iostream> using namespace std; int xx123; Some::Some() { xx123 = 20; } Some::~Some() { } void Some::prntf() { cout << "some:" << xx123 << endl;; }
当一个全局变量需要多文件中使用的时候,应当把这个变量的定义放在.cpp文件中而不是.h文件。
当然,或许有其他方法,欢迎指教。