如何定义一个变量(对象)让VC中所有源程序都能用。这里借助extern来实现。
我们知道extern的用法如是:
1
2 3 4 5 6 7 8 9 10 11 12
13
14 |
// a.h
extern
int a;
( extern) int 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.h和StdAfx.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; } |