C++ pass variable from .cpp to header file

戏子无情 提交于 2019-12-11 19:31:27

问题


this relates to a question i asked previously: C++ array in header file

in the main.cpp file there is a variable called fin1

ifstream fin1("ACW2_data.txt");

this might be a stupid question, but how can i use the value of this variable from main.cpp in the header file? (ie. is there a way to pass variables between the two files?)

any other info about using header files may help

Thanks in advance


回答1:


This variable can be declared in the header file as an extern.

extern ifstream fin1;

Now you can use this variable wherever you #include this header file including the header file itself. You don't need to pass the variable as such. :)




回答2:


I think you need to back up and explain what you are trying to do. Header files are, in general, for defining common definitions and declarations.

What do you mean by "use the value in the header file"? In general, the header file is not where code is run. So what needs to use this variable there?

Generally speaking, variables that need to be used in more than one file should be declared in the header to begin with. In C++, this is normally in the form of class members.

Even more common is to pass variables as arguments when another function or method needs to use the same value.

I can't tell from the information you've provided, but it sounds like you're on the wrong track to me.




回答3:


Declare this variable as extern .

extern ifstream fin1;

Than every time you change it it value gonna update and be ready in your header file And you can include tour header every where and use that variable



来源:https://stackoverflow.com/questions/5842583/c-pass-variable-from-cpp-to-header-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!