1. 程式人生 > 其它 >全域性變數和全域性靜態變數

全域性變數和全域性靜態變數

全域性變數和全域性靜態變數
作用域:
全域性變數整個程式空間,全域性靜態變數只在包含它的cpp中使用,下面舉個栗子

global.h
#ifndef GLOBAL_H
#define GLOBAL_H

static int gs_a;
extern int g_b; //multiple definition,注意extern

#endif // GLOBAL_H

testa.h

#ifndef TESTA_H
#define TESTA_H

class TestA
{
public:
    TestA();
};

#endif // TESTA_H

testa.cpp

#include "testa.h"
#include "global.h"
#include <iostream>

TestA::TestA()
{
    gs_a = 1;
    g_b = 1;
    std::cout << "TestA gs_a : " << gs_a << " g_b : " << g_b << std::endl;
}

testb.h

#ifndef TESTB_H
#define TESTB_H

class TestB
{
public:
    TestB();
};

#endif // TESTB_H

testb.cpp

#include "testb.h"
#include "global.h"
#include <iostream>

TestB::TestB()
{
    gs_a = 2;
    g_b = 2;
    std::cout << "TestB gs_a : " << gs_a << " g_b : " << g_b << std::endl;
}

main.cpp

#include <iostream>
#include "global.h"
#include "testa.h"
#include "testb.h"

int g_b = 0; //undefined reference to g_b,注意初始化
int main(int argc, char *argv[])
{
    gs_a = 3;
    g_b = 3;
    std::cout << "Main gs_a : " << gs_a << " g_b : " << g_b << std::endl;
    TestA ta;
    std::cout << "Main::TestA gs_a : " << gs_a << " g_b : " << g_b << std::endl;
    TestB tb;
    std::cout << "Main::TestB gs_a : " << gs_a << " g_b : " << g_b << std::endl;
    return 0;
}

輸出:

Main gs_a : 3 g_b : 3
TestA gs_a : 1 g_b : 1
Main::TestA gs_a : 3 g_b : 1
TestB gs_a : 2 g_b : 2
Main::TestB gs_a : 3 g_b : 2