1. 程式人生 > >關於一個檔案中的全域性變數在其他檔案中的使用

關於一個檔案中的全域性變數在其他檔案中的使用

錯誤:多重定義 和 xxx變數已經在xxx.obj中定義

當在一個.cpp檔案中定義了一個全域性變數之後,需要在其他檔案中使用時,需要用到關鍵字extern

當使用extern修飾一個變數時,例如extern int x;   代表當前變數x 的定義來自於其他檔案,當進行編譯時,會去其他檔案裡面找,

在當前檔案僅做宣告,而不是重新定義一個新的變數

main.cpp

#include <iostream>
#include "Some.h"
using namespace std;
 
extern int a;
int main() {
	Some * some = new Some;
	some->prntf();
	a= 50;
	cout << "main:" << a<< endl;;
	delete some;
	system("PAUSE");
	return 0;
}

Some.h

#pragma once
class Some
{
public:
	Some();
	~Some();
	void prntf();
};

Some.cpp

#include "Some.h"
#include <iostream>
using namespace std; 
int a;
 
Some::Some() {
	a= 20;
}
Some::~Some() {
 
}
 
void Some::prntf() {
	cout << "some:" << a<< endl;;
}

 當一個全域性變數需要多檔案中使用的時候,應當把這個變數的定義放在.cpp檔案中而不是.h檔案