VC中如何定义一个让所有源程序都能用的全局变量(对象)

如何定义一个变量(对象)让VC中所有源程序都能用。这里借助extern来实现。

我们知道extern的用法如是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
// a.h
extern  int a;
( externint f();

//a.cpp
int a =  0;
int f()
{
………
}

//b.cpp

#include “a.h”


如上几步便可以使b.cpp里直接引用a.h里面的a变量和int f()函数(函数前面extern可以省略);

所以,由于在VC中,我们的.cpp文件中都会包含#include "StdAfx.h",所以,我们可以把一个全局变量分别在StdAfx.hStdAfx.cpp中声明和定义,这样,我们就可以很方便的使用全局变量了。

附一例(vs2010):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//

#pragma once

#include  "targetver.h"

#include <stdio.h>
#include <tchar.h>

extern  int a;
extern  int testFun( int ax);
// TODO: 在此处引用程序需要的其他头文件

 // stdafx.cpp 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// stdafx.cpp : 只包括标准包含文件的源文件
// HelloWorld.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息

#include  "stdafx.h"

// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用

int a =  5;
int testFun( int ax)
{
     int result =  0;
    result = ++a;
     return result;
}

 // 主文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// HelloWorld.cpp : 定义控制台应用程序的入口点。
//

#include  "stdafx.h"
#include <iostream>
using  namespace std;

int _tmain( int argc, _TCHAR* argv[])
{
    cout << ++a << endl;
    cout << testFun(a) << endl;
    cout <<  "Hello World" << endl;

     return  0;
}
运行结果:



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值