在C ++中的多个文件中使用相同的变量 [英] Using the same variable across multiple files in C++

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

问题描述

在更改某些代码的过程中,我已经将一些功能溢出到了多个文件中.我有文件 controls.cpp display.cpp ,我希望能够访问两个文件中的同一组变量.我不介意在哪里初始化或声明它们,只要两个文件中的函数都可以使用它们.

In the process of changing some code, I have spilt some functions into multiple files. I have the files controls.cpp and display.cpp and I would like to be able to have access to the same set of variables in both files. I don't mind where they are initialized or declared, as long as the functions in both files can use them.

当函数位于同一文件中时,这不是问题,但是经过一个小时的谷歌搜索和各种尝试之后,现在看来几乎是不可能的.

This was not an issue when the functions were in the same file, but now it seems almost impossible after an hour of googling and trying various things.

推荐答案

在一个文件中定义变量,例如:

Define the variable in one file like:

type var_name;

并在另一个文件中全局声明它,例如:

And declare it global in the other file like:

extern type var_name;

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

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