extern关键字使用方法
extern可以在某种程度上替代#include "*.h"
参考:http://www.cnblogs.com/yc_sunniwell/archive/2010/07/14/1777431.html
示例1:使用extern替代#include "*.h"
CitedFile.h:
//pragma once
#ifndef __CITEDFILE_H__
#define __CITEDFILE_H__
extern char g_szData[]; //声明全局变量g_szData,可能会有其他文件引用
extern void g_func1();
#endif
CitedFile.cpp:
#include "stdafx.h"
#include "CitedFile.h"
#include <iostream>
using std::cout;
using std::endl;
char g_szData[] = "Can you believe it ?"; // 定义全局变量g_szData
void g_func1()
{
cout<<"============Using extern function===========\n";
cout<<g_szData<<"\n";
cout<<"========================================="<<endl;
}
Test4Rub.cpp:
#include "stdafx.h"
//#include "CitedFile.h"
#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>
int _tmain(int argc, _TCHAR* argv[])
{
extern char g_szData[];
cout<<"===========Using extern variable============\n";
cout<<g_szData<<"\n";
cout<<"===========================================\n"<<endl;
extern void g_func1();
g_func1();
system("pause");
return 0;
}
运行结果:

实例2:通过#include使用其他文件中的东西
修改含main入口的Test4Rub.cpp文件:
#include "stdafx.h"
#include "CitedFile.h"
#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>
int _tmain(int argc, _TCHAR* argv[])
{
//extern char g_szData[];
cout<<"===========Using extern variable============\n";
cout<<g_szData<<"\n";
cout<<"=========================================\n"<<endl;
//extern void g_func1();
g_func1();
system("pause");
return 0;
}
一样的结果。
一些不好的写法:
- 有些人喜欢把全局变量的声明和定义放在一起,这样可以防止忘记了定义,如把上面CitedFile.h改为extern char g_szData[] = "123456"; 然后把CitedFile.cpp中的定义去掉。
这个时候出现的问题是,如果通过#include来使用g_szData,那么会出现外部变量重定义错误。原因是:CitedFile.cpp中引入了CitedFile.h,这意味着g_szData[]被定义了一次,而Test4Rub.cpp也引入了CitedFile.h,这意味着g_szData[]又被定义了一次。
这个时候只能使用extern方法来使用。
解决方法:
只在.h文件中声明变量,真理永远这么简单。
总结:
提供方用extern声明,意在表明:可能外部会有某个文件使用该stuff;
使用方用extern声明,意在表明:我用的这个stuff在外面的其他文件中定义了。
疑问1:是不是extern使用于面向过程的开发,而不是用于面向对象的。因为如果面向对象的话,直接建立一个对象,引用其方法或属性即可啊。
C++的一个很大优势就是混合编程,比如一个很大的数组你指向开辟一次重复利用,那么你可以声明成extern全局的啊,这样的话,其他类的实现代码只需extern声明一下就可以使用了。
最后说一下extern不起作用的场合:static声明的变量(仅限于文件内部使用);但是,你硬性include进来,还是可以用的。你硬硬的复制了一份当然 可以用了。

浙公网安备 33010602011771号