我們經常看到extern這個關鍵字在代碼中,一般有兩個地方: 1. 頭文件中聲明一個全局變量。 2.是代碼中使用extern c。 1.頭文件中使用
#ifndef _XX_頭文件.H#define _XX_頭文件.Hint A;#endif例如上面的代碼,如果這樣定義一個全局變量,那么如果這個頭文件被多次引用,那么這個全局變量A就會多次被定義,所以為了解決這個問題,需要使用關鍵字extern。
#ifndef _XX_頭文件.H#define _XX_頭文件.Hint A;#endif完整代碼如下: extern.h
#ifndef __EXTERN_H__#define __EXTERN_H__extern int a;#endifextern.cpp
#include "extern.h"int a = 2;test1.h
#include "extern.h"#include <iostream>using namespace std;void fun1();test1.cpp
#include "extern.h"#include "test1.h"void fun1(){ //a = 1; cout << a << endl;}test2.h
#include "extern.h"#include <iostream>using namespace std;void fun2();test2.cpp
#include "extern.h"#include "test2.h"void fun2(){ //a = 2; cout << a << endl;}main.cpp
#include "test1.h"#include "test2.h"int main(){ fun1(); fun2(); system("pause"); return 0;}新聞熱點
疑難解答