C++ 跨文件使用全局变量

使用方法

在头文件中声明变量,在cpp文件中使用。

声明时使用extern关键字 告诉编译器去其他文件中寻找

示例代码

test.h

#ifndef TEST_H
#define TEST_H

int global_v;

#endif

test.cpp

#include <iostream>
#include "test.h"

using namespace std;

int global_v = 1;

void modify()
{
    global_v++;
    cout << "in test, value increases to " << global_v << endl;
}

main.cpp

#include <iostream>
#include "test.h"

using namespace std;

extern int global_v;

int main()
{
    cout << "in main, value is " << global_v << " before modify" << endl;

    modify();

    cout << "in main, value is " << global_v << " after modify" << endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/flyconley/article/details/119107750