Thomas_36 0 Newbie Poster

I am trying to create a header file that contains several global variables. At the moment, the Globals header file looks like this:

This is Globals.h

#ifndef GLOBALS_INCLUDED
#define GLOBALS_INCLUDED

#include <string>

std::string DRIVE="HELLO!!!!!";

#endif

To go along with this, I have a cpp and h file the contain a single function, as follows:
This is Bull.h

ifndef BULL_H
#define BULL_H

#include "Globals.h"
#include <iostream>

int po(int x);

#endif

and
This is Bull.cpp

#include "bull.h"

int po(int x)
 {
     extern std::string DRIVE;
     std::cout << DRIVE << "\nBULL\n";
     DRIVE="BULL\n";
     return 1;
 }

Finally, the main execution program, main.cpp:

#include <iostream>
#include "Globals.h"
#include "bull.h"

using namespace std;
//extern std::string  DRIVE="Hello";

int main()
{
    extern std::string DRIVE;
    po(3);

    cout << DRIVE << " Hello world!" << endl;
    po(3);
    return 0;
}

When I try to compile the program as written above, I get an error which states that there are multiple definitions of DRIVE at the start of the main function.

If I delete the line #include "Globals.h" from the Bull.h file everything compiles and runs as expected.

I wrote these files to learn about the extern command used with global variables defined in a different file. But, the problems I am getting smack of compiler directive problems. So, I am not sure if I have learned anything yet.

My questions:

I believe I am doing the #ifndef and #define and compile directives properly so that multiple versions of a header do not occur within the compiled program. But, if I am, then shouldn't the header calls for bull.h in both main.cpp and bull.cpp be acceptable? If so, why am I getting a multiple defintions error when I do that.

As an added wrinkle, when I delete #include "Globals.h" and restore in bull.h I again get a multiple definition compile error, but this time it occurs at the first line of the function po in the file bull.cpp.

It would appear that the header file Globals.h can only be called once, and then only in the main.cpp file. The second file, bull.cpp, that uses the defintions in Globals cannot have that header declared within its header. Nor can I include Globals.h within the bull.cpp file -- that causes a multiple defintion of DRIVE error too.

Finally, back to learning about global variables and extern, I tried to intialize the variable DRIVE in the main.cpp file, but that did not work. You can see that the line is now commented out. Is there a way to do this?

So, what am I missing here?

Probably something simple, but I cannot figure it out.

Thanks for your help.