-2

Whenever I run the code it just comes out as what was put in the first .cpp file and ignores everything from the other one.

main.cpp:

#include <iostream>
#include "variables.h"
#include "intro.cpp"

using namespace std;

float gold;

int main()
{
  float gold = 0;

  intro();

  cout<<gold;

  return 0;
}

intro.cpp:

#include "variables.h"

void intro()
{
  gold = 5.0;
}

header:

#ifndef VARIABLES_H_
#define VARIABLES_H_

extern float gold;

#endif

It always outputs gold as 0 instead of 5. What am I doing wrong?

273K
  • 29,503
  • 10
  • 41
  • 64
Wdoug
  • 27
  • 4

1 Answers1

2
int main()
{
    float gold = 0;
    ...
    cout<<gold;
}

You declared yet another variable gold, local, and print out it.

Remove the local variable declaration:

int main()
{
    ...
    cout<<gold;
}

Or print out the global variable:

int main()
{
    float gold = 0;
    ...
    cout << ::gold;
}

I recommend you to read Why should I not include cpp files and instead use a header?

273K
  • 29,503
  • 10
  • 41
  • 64