声明(declaration),指定了变量的类型与名称。声明的目的是为了让变量名对程序而言是已知的。
定义(definition),不仅要指定变量的类型和名称,还要分配存储空间,甚至提供初始值。同时,定义也是声明。
既然变量定义已经包括变量声明的功能了,为何还要变量声明呢?
存在变量声明是为了支持单独编译(separate compilation)。单独编译允许文件A中的代码能够使用在文件B中定义的变量mystring。声明的存在是为了告诉编译器:文件A中的变量mystring定义在了其他的文件中,请先编译文件A,待遇到变量mystring的定义后,再给文件A的变量mystring分配存储空间或赋值。
举个例子:
B.h
#include <iostream>
#include <string>
using std::string;
void Printmsg(string x);
B.cpp
#include <iostream>
#include "B.h"
extern string mystring;
extern string mystring2="error";
void Printmsg(string mystr){
std::cout<<"你刚刚输入的是:"<<mystr;
}
A.cpp
#include <iostream>
#include "B.h"
using namespace std;
string mystring="hello word";
//string mystring2="error0";
int main()
{
Printmsg(mystring);
return 0;
}