0

I've got aud.ccp, aud.h, geist.ccp, geist.h. In geist.ccp I've got a variable which needs to get to aud.ccp.

If I got:

int x = 5;

in geist.ccp, how can I achieve it, that a 8 gets represented in the console when I use

cout << x+y << endl;

as well as

cin >> y; // ofc I enter 3 here.

in aud.ccp.

Edit: I wrote:

int x

in the public part of geist.h and I wrote:

x = 5;

in geist.cpp. Finaly I wrote

extern int x;

in aud.cpp

But somehow I do not get the result I want

Henrik_F
  • 9
  • 2

2 Answers2

1

You need to declare the variable in a public scope of one module:

int x;

and declare its use in another one:

extern int x;

Then both modules, when linked together, will use the same variable.

It's most conveniently done with the defining declaration (with an optional initializer) placed in a .cpp module, and the extern declaration put into a .h file. Then each module, both the one defining the variable and those importing it, see the same extern declaration, which guarantees the declaration is same as an actual definition of the variable.

CiaPan
  • 9,381
  • 2
  • 21
  • 35
0

You have to care about "redefinition x variable Error" in your code. You can Try this method:

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";
}

aud.h:

#ifndef AUD_H
#define AUD_H

extern int x;
void Add_X_with_User_Desire();

#endif

aud.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";
}

and finally main function:

stack59228825.cpp:

#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();

}

  • Such geist.h doesn't make much sense. If you include it into two or more modules, the public `x` variable will be declared multiple times, causing linking error. And if you include it just once into geist.cpp then you don't need the .h file - just put its contents into the .cpp file.... – CiaPan Dec 08 '19 at 18:52