Variable scope problem?

Hi.. I'm following an example in my book but the code doesn't compile for me, it gives me errors.

My errors are
C:\Users\george\Programming\C++\PrimerPlus\practice\main.cpp|4|error: redefinition of 'int dick'|
C:\Users\george\Programming\C++\PrimerPlus\practice\coordin.h|3|error: 'int dick' previously defined here|
C:\Users\george\Programming\C++\PrimerPlus\practice\main.cpp|5|error: redefinition of 'int harry'|
C:\Users\george\Programming\C++\PrimerPlus\practice\coordin.h|4|error: 'int harry' previously defined here|
||=== Build finished: 4 errors, 0 warnings ===|


The issue I'm having is that I want dick & tom still be usable from other files so I don't want to prefix them with static.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//main.cpp
#include <iostream>
#include "coordin.h"
int tom = 3; // external variable definition
int dick = 30; // external variable definition
static int harry = 300; // static, internal linkage

void remote_access();
int main()
{
    using namespace std;
    cout << "main() reports the following addresses:\n";
    cout << &tom << " = tom, " << &dick << "  = &dick, ";
    cout << &harry << " = &harry\n";
    remote_access();
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
//coordin.h
#include <iostream>
extern int tom; // tom defined elsewhere
static int dick = 10; // overrides external dick
int harry = 200; // external variable definition, no conflict with twofile1 harry

void remote_access()
{
    using namespace std;
    cout << "remote_access() reports the following addresses:\n";
    cout << &tom << " = &tom, " << &dick << " = &dick, " << &harry << " = &harry\n";
}
When you include a *.h file it is pretty much the same thing as including all of the code in that #include at the start of your *.cpp file.

Remove these lines from your main.cpp to make your code work:
1
2
int dick = 30;
static int harry = 300;


Alternatively, use extern in front of dick and harry in the .cpp file and remove the static keywords.

For a better solution follow these steps:
1. Remove all current definitions of tom, dick and harry from the .h and .cpp files.
2. Define tom, dick and harry in the main() function.
3. Pass tom, dick and harry into remote_access() as arguments.
Topic archived. No new replies allowed.