C基础之static extern

//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;
}

输出为:

fistsecondthird
compile error00
int g_count 已经在 b.cpp.obj 中定义11
找到一个或多个多重定义的符号14

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值