Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent a source file from depending on an include inside a header file?

Tags:

c++

//Foo.h
#include <string>
struct Foo;

//main.cpp
#include "Foo.h"
int main(int argc, char *argv[])
{
  std::string s = "hello";
}

The problem I have with this code is that #include <string> leaks into main.cpp. #include <string> is needed in main.cpp to compile but if in a future version Foo.h doesn't need string anymore, main.cpp will not compile.

Is there a way to prevent this?

Edit: I know that I can manage this on my own by always including every file that I need but I am working in a team and everyone does their own thing and it is a complete mess. So I was wondering if there is a way to force this.

Comments seem to indicate that we have to manage it manually. I guess this answers my question.

like image 508
Maik Klein Avatar asked Oct 25 '25 15:10

Maik Klein


1 Answers

No, there is no automated way to protect yourself from inadvertently relying on headers that you've included through other headers.

What you need to do is discipline yourself to include the relevant headers in each source file that uses them, even if each #include directive isn't strictly required in each source file.

The consequences of forgetting that aren't dire, though. If Foo.h eventually changes to no longer include string, then the code will fail to compile, but the fix is easy and takes almost no time. It's not worth worrying about.

like image 60
Rob Kennedy Avatar answered Oct 27 '25 05:10

Rob Kennedy