如何在其他文件(foo.h,foo.cpp)中使用主文件(main.cpp)中的变量?

时间:2018-02-16 09:37:10

标签: c++ variables

如何在其他文件(main.cppfoo.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

1 个答案:

答案 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并使用aabb