C++ 在不同文件之间传输变量

C++ 在不同文件之间传输变量,c++,C++,我有aud.ccp,aud.h,geist.ccp,geist.h。在geist.ccp中,我有一个变量需要进入aud.ccp 如果我得到: int x = 5; 在geist.ccp中,当我使用 cout << x+y << endl; 在aud.ccp中 编辑: 我写道: 在geist.h的公共部分 我写道: x = 5; 在geist.cpp中。 最后我写了 extern int x; 以澳元计算 但不知何故,我没有得到我想要的结果您需要在一个模块的公共范围

我有
aud.ccp
aud.h
geist.ccp
geist.h
。在
geist.ccp
中,我有一个变量需要进入
aud.ccp

如果我得到:

int x = 5;
geist.ccp
中,当我使用

cout << x+y << endl;
aud.ccp

编辑: 我写道:

在geist.h的公共部分 我写道:

x = 5;
在geist.cpp中。 最后我写了

extern int x;
以澳元计算


但不知何故,我没有得到我想要的结果

您需要在一个模块的公共范围内声明变量:

int x;
并在另一个项目中声明其用途:

extern int x;
然后,当两个模块链接在一起时,将使用相同的变量

最方便的方法是将定义声明(带有可选的初始值设定项)放在
.cpp
模块中,将
extern
声明放在
.h
文件中。然后,每个模块(定义变量的模块和导入变量的模块)都会看到相同的
extern
声明,这保证了声明与变量的实际定义相同。

您必须注意代码中的“重新定义x变量错误”。 您可以尝试以下方法:

geist.h:

#ifndef GEIST_H
#define GEIST_H

int x {5};

#endif
geist.cpp:

#include "geist.h"
#include <iostream>
using namespace std;

void printname()
{
    cout << "The X value is" << x <<"\n";
}
澳元.cpp:

#include "aud.h"
#include <iostream>
using namespace std;

void Add_X_with_User_Desire()
{
    int y{0};
    cout << "Please Enter an Integer Number: "<< "\n";
    cin >> y;
    cout << "y + x: " << x+y<<"\n";
}
#包括“aud.h”
#包括
使用名称空间std;
void Add_X_with_User_Desire()
{
int y{0};
库蒂;

这样的geist.h没有多大意义。如果将它包含到两个或多个模块中,public
x
变量将被多次声明,从而导致链接错误。如果只将它包含到geist.cpp中一次,则不需要.h文件-只需将其内容放入.cpp文件中。。。。
#include "geist.h"
#include <iostream>
using namespace std;

void printname()
{
    cout << "The X value is" << x <<"\n";
}
#ifndef AUD_H
#define AUD_H

extern int x;
void Add_X_with_User_Desire();

#endif
#include "aud.h"
#include <iostream>
using namespace std;

void Add_X_with_User_Desire()
{
    int y{0};
    cout << "Please Enter an Integer Number: "<< "\n";
    cin >> y;
    cout << "y + x: " << x+y<<"\n";
}
#include <iostream>
#include "aud.h"

int main()
{
    std::cout <<"X variable in main function is:" <<x << "\n";
    Add_X_with_User_Desire();

    x = 10;
    std::cout << "targetVariable in main function is:" << 10 << "\n";
    Add_X_with_User_Desire();

}