This question already has answers here:
Global Variable within Multiple Files
(3个答案)
去年关闭。
如何使用主文件(
确实没有必要编写任何代码,但我将发布一些代码来帮助澄清我的问题。
然后,您可以只包含
(3个答案)
去年关闭。
如何使用主文件(
main.cpp
)和其他文件(foo.h
,foo.cpp
)中的变量?确实没有必要编写任何代码,但我将发布一些代码来帮助澄清我的问题。
main.cpp
#include<iostream>
#include<foo.h>
using namespace std;
int aa = 10;
int bb = 20;
Foo xyz;
int main() {
cout<<"Hello World"<<endl;
xyz.doSomething();
return 0;
}
foo.h
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
void doSomething() {
int abc = aa + bb;
cout<<"aa + bb = "<<abc<<endl;
};
};
#endif // FOO_H
最佳答案
您应该声明一个main.h
文件,在其中声明您的变量,然后在main.cpp
中声明它。所以你会main.h
extern int aa, bb;
main.cpp
#include "main.h"
#include <iostream>
#include <foo.h>
using namespace std;
int aa = 10;
int bb = 20;
Foo xyz;
int main() {
cout<<"Hello World"<<endl;
xyz.doSomething();
return 0;
}
然后,您可以只包含
main.h
并使用aa
和bb
关于c++ - 如何在其他文件(foo.h,foo.cpp)中使用主文件(main.cpp)中的变量? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48823792/