Problem is, it appears the #ifndef and #define tags aren't stopping Secondary.cpp from redeclaring HelloWorld.
Does anyone know what I did wrong?
Your include guard is correct, but it is designed for a different kind of problem, like this:
// Main.cpp
#include "Main.h"
#include "Main.h"
int main()
{
cout << HelloWorld;
//HelloEarth();
}
The above code will still compile fine because you've protected against Main.h being included more than oncein the same compilation unit.
Each CPP file is a separate compilation unit, so both Main.cpp and Secondary.cpp are going to be able to include Main.h , even with the include guard.
The error message actually says multipledefinition, not declaration. The problem isn't that you've declared HelloWorld in the header, it's that you've given it a value there. Because each CPP file includes the header separately, you've given it a value twice--this is what the compiler's complaining about.
You can stilldeclare HelloWorld in Main.h , and you must if you want to refer to it from multiple CPP files, but you can only give it a value in one place. It doesn't really matter where, as long as the file that contains the definition is compiled into the final executable.
Here's one way you could do it:
// Main.h
#ifndef MAIN_H
#define MAIN_H
#include <iostream>
using namespace std;
#include <string.h>
extern string HelloWorld;
void HelloEarth();
#endif
// Main.cpp
#include "Main.h"
string HelloWorld = "Hello World!\n";
int main()
{
cout << HelloWorld;
HelloEarth();
}
// Secondary.cpp
#include "Main.h"
void HelloEarth()
{
cout << HelloWorld;
}
Note the use of extern . That's basically telling the compiler, "Hey, there's a string called 'HelloWorld', but it's defined somewhere else." If you don't use this keyword, you'll get the same "multiple definition" error, because even if you don't give it a value explicitly, it still gets one--in this case, the empty string.
With extern , both Main.cpp and Secondary.cpp know that HelloWorld is a string and can use it as such. If you forget to give HelloWorld a value somewhere, you'll get a linker error--the compiler is perfectly happy.