//a.h
// int g_count; // first
// static int g_count; // second
extern int g_count; // third
void addCount(int);
// a.cpp
#include "a.h"
int g_count; // third
// if no this, 无法解析的外部符号int g_count
// b.cpp
#include "a.h"
void IncrCount(void)
{
g_count += 1;
}
int main()
{
cout << g_count << endl;
IncrCount();
cout << g_count << endl;
addCount(3);
cout << g_count << endl;
return 0;
}
输出为:
fist | second | third |
compile error | 0 | 0 |
int g_count 已经在 b.cpp.obj 中定义 | 1 | 1 |
找到一个或多个多重定义的符号 | 1 | 4 |
C++ static关键字使用问题,static关键字主要是 用来将变量限定在该文件中作用域,对于second场景,如果放在.h头文件中,那么include该头文件的所有文件中,会存在多份static 内存变量,虽然名字一样,但是内存不同,造成了以上问题,以为是修改同一全局变量,但是并不是想要的结果。
输出结果为
//a.h
//int g_a; // 找到一个或多个多重定义的符号
static int g_b; // second
extern int g_c; // third
void AddCount(int);
//a.c
#include "classA.h"
//int g_a; // Redefinition of 'g_a'
//int g_b; // Non-static declaration of 'g_b' follows static declaration
int g_c; //
void AddCount(int count)
{
//g_a += count;
g_b += count;
g_c += count;
}
//b.c
#include <stdio.h>
#include "classA.h"
void IncrCount(void)
{
//g_a++;
g_b++;
g_c++;
}
void Test(void)
{
printf("g_a is %d, g_b is %d, g_c is %d\n", 0, g_b, g_c);
IncrCount();
printf("g_a is %d, g_b is %d, g_c is %d\n", 0, g_b, g_c);
//printf("g_a is %d, g_b is %d, g_c is %d\n", g_a, g_b, g_c);
AddCount(3);
printf("g_a is %d, g_b is %d, g_c is %d\n", 0, g_b, g_c);
//printf("g_a is %d, g_b is %d, g_c is %d\n", g_a, g_b, g_c);
}
g_a is 0, g_b is 0, g_c is 0
g_a is 0, g_b is 1, g_c is 1
g_a is 0, g_b is 1, g_c is 4