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

C++ 如何在其他文件(foo.h、foo.cpp)中使用我的主文件(main.cpp)中的变量?,c++,variables,C++,Variables,如何在其他文件(foo.h,foo.cpp)中使用主文件(main.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

如何在其他文件(
foo.h
foo.cpp
)中使用主文件(
main.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;
}
#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
文件,在那里声明变量,然后在
main.cpp
中声明它。所以你会

main.h

extern int aa, bb;
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;
}
#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”
#包括
#包括
使用名称空间std;
int aa=10;
int-bb=20;
Foo-xyz;
int main(){

cout您应该声明一个
main.h
文件,在那里声明您的变量,然后在
main.cpp
中声明它

main.h

extern int aa, bb;
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;
}
#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”
#包括
#包括
使用名称空间std;
int aa=10;
int-bb=20;
Foo-xyz;
int main(){

这真是个糟糕的主意。不要这样做。将它们作为参数传递。你能提供一个链接或给出一个例子吗?-简单的回答是,拥有全局变量使创建小型、自包含的可组合解决方案变得不可能。但编写小型、自包含的解决方案是编写复杂程序的唯一方法因为人类的大脑很小,不能一下子想到整个程序。这是一个非常糟糕的主意。不要这样做。将它们作为参数传递。你能提供一个链接或举个例子吗?-简单的回答是,拥有全局变量使创建小型、自包含的可组合解决方案变得不可能。但组合small、 自包含的解决方案是编写复杂程序的唯一方法,因为人类的大脑很小,不能一次想到整个程序。“稍后在main.cpp“->”中声明,稍后在main.cpp中定义”我想我明白你的意思。但是我是否应该在我的main.cpp中包含
main.h
?全局变量通常是你应该尽量避免的。在我看来,这可能是一个有效的示例,但非常糟糕。@默认情况下,是的,我非常同意。这是非常糟糕的代码,但这是对这个问题的答案。请不要这样做,将变量作为参数并避免全局变量。@JeromeReinländer那么为什么不将其添加到您的问题中?“并稍后在main.cpp“->”中声明它,然后在main.cpp中定义它”我想我明白你的意思。但是我是否应该在我的main.cpp中包含
main.h
?全局变量通常是你应该尽量避免的。在我看来,这可能是一个有效的示例,但非常糟糕。@默认情况下,是的,我非常同意。这是非常糟糕的代码,但这是对这个问题的答案。请不要这样做,将变量作为参数和避免全局变量。@JeromeReinländer那么为什么不把它添加到你的问题中呢?