如何在其他文件(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
答案 0 :(得分:3)
您应该声明一个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