I’ve been programming for awhile now and one thing I’ve still never quite figured out is exactly when you need to #include something. I know to be safe you can do it whenever you use something declared in another file. However at times I find that I can remove an #include and everything will still compile just fine. From what I can tell this is because other files being included already are including the external definition. There are two particular cases I’m interested in knowing the behavior for:
-
Say we have three .h/.cc pairs: f1.h/.cc, f2.h/.cc, and f3.h/.cc. If f2.h/.cc includes f1.h and f3.h/.cc includes f2.h is it ever necessary for f3.h/.cc to include f1.h or will all of f1.h’s definitions be visible to the f3 files when it is included in f2?
-
Once again say we have three .h/.cc pairs: f1.h/.cc, f2.h/.cc, and f3.h/.cc. If f2 includes f1 and f2 includes f1 and then f3 includes f1 or f2 will the “circular linkage” between and f1 and f2 cause a problem?
Do you know of any good resources online I can read to better understand how including something in one file affects subsequent files in the project?
There is nothing much to it. If you use something, you have to include the header declaring the thing you use. About the only exception is forward declaring a class/struct or method like:
if you just need to declare a pointer or reference to the class.
You cannot really rely on other headers including the header you need, by chance. Any day, the maintainer of the other header will realize that he/she don’t need that include anymore and remove it.