MFC工程中 定义一个变量让所有源程序都能用的最简单的方法
2014-04-03 22:36
363 查看
如何定义一个变量(对象)让VC中所有源程序都能用。这里借助extern来实现。
我们知道extern的用法如是:
如上几步便可以使b.cpp里直接引用a.h里面的a变量和int f()函数(函数前面extern可以省略);
所以,由于在VC中,我们的.cpp文件中都会包含#include
"StdAfx.h",所以,我们可以把一个全局变量分别在StdAfx.h和StdAfx.cpp中声明和定义,这样,我们就可以很方便的使用全局变量了。
附一例(vs2010):
// stdafx.cpp
// 主文件
运行结果:
我们知道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” |
所以,由于在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: 在此处引用程序需要的其他头文件 |
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 val) { int result = 0; result = ++val; 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; } |
相关文章推荐
- Android的一些疑问
- Java中的i++探讨
- flex模块发布后白屏,有可能是bug问题
- 【设计模式】设计模式之适配器模式
- 4种检测是否支持HTML5的方法,你知道几个?
- 最长公共子串 NYOJ 36
- ffmpeg
- tomcat server.xml配置详解
- leetcode之Linked List Cycle
- image project
- 黑马程序员 C语言-----指针学习
- 学习SpringMVC系列教程(一)Spring MVC入门
- 防止硬盘数据泄漏
- 3.取色精灵V2.0-非模态对话框自建消息队列、VS2008风格对话框、使用Common Controls、悬浮透明窗口、使用SLIDER控件
- 动念头易,坚持学习不易,且学且珍惜
- EChart 制作类似微软的 甘特图
- DOM4j解析xml文件
- sip协议理解
- java web 项目实现 耦合-解耦 解决方案----工厂模式入门级别
- android BroadcastReceiver