I have these enums declared and defined in globals.h:
1 2 3 4 5 6 7 8 9
// I enclosed the enum in a namespace to avoid warnings about ambiguity of just "match" - "match::match" is less vague
namespace match {
enum match {
correct,
incorrect,
dispute,
TERMINATE
};
}
I know that if I wanted to use that enum as variable type, I would need to forward declare said variable in that same header file like this:
match::match var;
But what I want to do is to use the enum as return type for a function in a completely different file (so neither globals.h nor globals.cpp). Function resides in word.cpp and its prototype in word.h:
word.h
1 2 3 4 5 6 7 8
#ifndef WORD_H
#define WORD_H
match::match give_word(arguments' types);
/* I presume headers don't need including "globals.h"? since it will be pasted in word.cpp anyway */
// edit: I included "globals.h" in "word.h" but it didn't get rid of the errors
#endif WORD_H
word.cpp
1 2 3 4
#include "globals.h"
#include "word.h" // this way I ensure that enum definition (in globals.h) gets loaded first, before it is used in the function prototype (word.h) and the function definition below (word.cpp)
match::match give_word(arguments) { stuff }
But the compiler always complains about match not being a type or that match:match is invalid because the first match:: is not a typename or a class.
Let's say I use <string> library in both word.cpp and word.h - do I include <string> library only in the header, or both?
In a similar vein, if I have a "file.h", do I include it in the .cpp or .h file? I've heard about something called circular dependency and I'm wary of including files too often. Could somebody explain it to me? The only examples I found were using classes and whatnot, and I'm not on that level yet.
do I include <string> library only in the header, or both?
Include where it's used. If both files use it, both files include it.
I've heard about something called circular dependency and I'm wary of including files too often. Could somebody explain it to me? The only examples I found were using classes and whatnot
Circular dependency between classes, circular dependency between files, and circular dependency between libraries are slightly different things, although similar at bird's eye view level: A needs B and simultaneously B needs A.
"including files too often" won't be a problem unless the files are missing include guards - your files have them (#ifdef WORD_H etc), so it's fine.
#ifndef MY_GLOBAL
#define MY_GLOBAL
// I enclosed the enum in a namespace to avoid warnings about ambiguity of
// just "match" - "match::match" is less vague
namespace match {
enum match {
correct,
incorrect,
dispute,
TERMINATE
};
}
#endif // MY_GLOBAL