多个文件中的全局变量 [英] Global Variable within Multiple Files

查看:123
本文介绍了多个文件中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个源文件需要访问一个公共变量。什么是最好的方法做到这一点?例如:

I have two source files that need to access a common variable. What is the best way to do this? e.g.:

source1.cpp:

source1.cpp:

int global;

int function();

int main()
{
    global=42;
    function();
    return 0;
}

source2.cpp:

source2.cpp:

int function()
{
    if(global==42)
        return 42;
    return 0;
}

如果变量global的声明是static,extern,在这两个文件包含的头文件中,etc?

Should the declaration of the variable global be static, extern, or should it be in a header file included by both files, etc?

推荐答案

全局变量应声明 extern 在两个源文件包含的头文件中,然后只在其中一个源文件中定义:

The global variable should be declared extern in a header file included by both source files, and then defined in only one of those source files:


strong> common.h



extern int global;




source1.cpp



#include "common.h"

int global;

int function(); 

int main()
{
    global=42;
    function();
    return 0;
}




source2.cpp



#include "common.h"

int function()
{
    if(global==42)
        return 42;
    return 0;
}

这篇关于多个文件中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆