C++编程思想 第1卷 第3章 指定存储空间分配 外部变量

extern关键字告诉编译器存在一个变量和函数,即使编译器在当前文件没有看到它。

这个变量或函数可能在另一个文件中或者在当前文件后面定义


//: C03:Forward.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Forward function & data declarations
#include <iostream>
using namespace std;

// This is not actually external, but the 
// compiler must be told it exists somewhere:
extern int i; 
extern void func();
int main() {
  i = 0;
  func();
  getchar();
}
int i; // The data definition
void func() {
  i++;
  cout << i;
} ///:~


遇到'extern int i'时,知道i肯定作为全局变量在某处
当编译器看到变量i的定义时,并没有看到别的声明
如果i定义为static,又要告诉编译器,i是全局定义的(通过extern)。
但是static,有文件作用域,编译器会产生错误。


输出
1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值