全局变量不工作 [英] global variable doesn't work

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

问题描述

我有一个全局 int 我想更改不同的文件,由于某种原因它不工作。

I have a global int I want to change in different files, for some reason it doesn't work.

我有:

// test.h

//test.h

 #include <windows.h>

static int start1; //want to use this globally.

//declare
void something();

// test.cpp

//test.cpp

#include "test.h" 

extern int start1;

void something()
{
    start1 = start1 + 1;
}

// main.cpp

//main.cpp

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

int _tmain(int argc, _TCHAR* argv[])
{
    start1 = 3;
    something();
    return 0;
}

为什么,当你进入 something / code>是 start1 0,而不是3?我一直在试图使一个全局变量小时,它不工作。

Why, when you go into something() is start1 0, instead of 3? I have been trying to make a global variable for hours, and it doesn't work. Please can someone clarify?

推荐答案

不要声明 static 变量在头文件中。这将导致为包含该头文件的每个翻译单元(即源文件)存在单独的变量。

Don't declare a static variable in a header file. That will result in a separate variable existing for each translation unit (i.e. source file) that includes that header file.

规范模式是将变量声明为 extern ,然后在一个源文件中定义正常。

The canonical pattern is to declare the variable as extern in the header file, and then define it "normally" in one source file.

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

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