我有一个全局int我想要在不同的文件中更改,由于某种原因它不起作用.
我有:
//test.h
#include <windows.h>
static int start1; //want to use this globally.
//declare
void something();
Run Code Online (Sandbox Code Playgroud)
//test.cpp
#include "test.h"
extern int start1;
void something()
{
start1 = start1 + 1;
}
Run Code Online (Sandbox Code Playgroud)
//main.cpp
#include "test.h"
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
start1 = 3;
something();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么,当你进入something()是start10而不是3?我一直试图制作一个全局变量几个小时,但它不起作用.请有人澄清一下吗?
Oli*_*rth 10
不要static在头文件中声明变量.这将导致为包含该头文件的每个翻译单元(即源文件)存在单独的变量.
规范模式是extern在头文件中声明变量,然后在一个源文件中"正常"定义它.