3 ms·
> In reality, because there are no hard rules, people do anything. You get definitions mixed into headers and such. All of that is done so forward declaration
by sumtechguy 2y ago
> In reality, because there are no hard rules, people do anything. You get definitions mixed into headers and such.
All of that is done so forward declaration works.
The problem is #include does just what it says on the tin. It includes whatever is in the file into the file the #include is in. By convention that is .h/.hpp for headers. But there is nothing saying it can not be something like #include<'somerandom.jpg'> or even another .cpp file (seen it). Now that probably will not compile. But the pre-processor will include it at the spot you say. Then promptly barf on it because it does not parse.
The compiler says anything you declare though needs to be defined. Usually a built in type, or class, or struct, or typedef. Basically defined before use. So technically I can glom all of my stuff together and if I get it in the right order I could have one giant file and zero new headers. But we like our class/function files to be semi organized so forward declaring items is the norm.
C++ adds a bit of a twist on all of this. In that a class file does not have to be all in one spot. It can be in a header or smeared across 20 other files. The one rule the linker needs is hey is this declared before you use it. That way the linker can eventually find the right code to call.
To understand the 'why' you have to understand the linker and preprocessor work together to make it happen.
- epcoa 2y ago> The compiler says anything you declare though needs to be defined. No it doesn’t. If that were true dynamic linking would not be a thing, but it’s not even true in the most basic way either. > Basically defined before use. Also not true. But this is “not even wrong” since “before use” isn’t defined here, however if it is meant to be appears before in the input, then that is wrong. > The one rule the linker needs is hey is this declared before you use it. That way the linker can eventually find the right code to call. Because of the way C++ is defined this is somewhat true (not so much for incomplete types), but also a tortured avoidance of the compiler role (Translation phase 7) in the process, and really the meat of what is going on. I’d recommend someone just read cppreference first. https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration https://stackoverflow.com/questions/1410563/what-is-the-diff...