I have eliminated two header inclusions in a translation unit using extern. Is this advisable?
My specific situation: I have a class called ParseTree that accumulates Token*‘s. ParseTree* is a private member of Parser.
Initially, I had the following lines in parse_tree.cc.
#include "parser.h"
#include "token.h"
After analyzing my code, I isolated the two functions that actually had external dependencies and replaced the includes with the following:
extern std::ostream& operator<<(std::ostream& out, const Token& t); // @token.h
extern bool hasPriority(const Token* p_tok1, Token* p_tok2); // @parser.h
Both solutions appear to work. Are there any hidden dangers of which I should be aware when selecting extern over include?
If you use
externdeclarations, you’re unnecessarily repeating yourself by restating the prototype of the function everywhere you use it. With a header file, if you want to change the prototype, you only need to change it in one place.So no, don’t use
externwhen you already have a suitable header file.