前言:
虽然是一个很基础的东西,但是在实际使用中是很频繁的,所以感觉有必要单独说明记录一下。
操作步骤:
1、创建win32工程,包含有基础的main函数(当作A文件):main.cpp
2、创建新的cpp文件以及头文件,当作B文件:Test1.cpp Test1.h
3、在B文件中随意写一个函数以及几个变量,以便在A文件中调用:printTest() g_num、g_name、g_b
完整示例代码:
main.cpp
// global_variable.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Test1.h"
//by zhaocl
int main()
{
g_b = true;
printf( "g_num:%d \n", g_num );
printf( "g_name:%s \n", g_name );
printTest();
getchar();
return 0;
}
Test1.cpp
#include "stdafx.h"
#include "Test1.h"
#include "string.h"
int g_num = 0;
char * g_name = NULL;
bool g_b = false;
//function
void printTest()
{
//int
int num = 100;
g_num = num;
//char
/*char *str1 = "zhaocl";
g_name = str1;*/
char str2[] = "zhaocl";
g_name = new char[100];
strcpy( g_name, str2 );
//bool
if( g_b )
{
printf( "this is test1.\n" );
}
else
{
printf( "this is no.\n" );
}
}
Test1.h
#pragma once
void printTest();
extern bool g_b;
extern int g_num;
extern char *g_name;
总结:
1、函数调用:头文件中声明后,在使用的地方加上头文件即可使用
2、变量调用:使用全局变量,头文件中extern声明,cpp中定义,在使用的地方加上头文件即可使用