This is a brain-dead newbie question, but here goes:
What determines what files get included in a C/C++ project?
My understanding is that the compiler starts with the file that has main() in it and that file will contain #include’s to get various h files which contain #include’s to other h files and so on until everything is included in the project.
My questions:
What is the relationship between h files and cpp files of the same name? I mean, of course I understand that code-wise they need each other and the cpp file always (almost always?) #include’s the h file, but from the compiler’s point of view is it important for them to have the same names or is this all just a convention? Can I include extra cpp files without corresponding h files?
Also, when the project is built and linked, how does it know which cpp/h files to build object files for? Will it just start at the cpp file with “main()” in it and keep going through #include’s until it has everything it needs and build all of that, or does it just build everything that a user specifies in the makefile or in the IDE project file?
Finally, when the linker finally comes around and links all the object code to make an executable, is there a special order it arranges everything in?
Any help, hints, explanations appreciated..
Thanks!
–R
Think of files as just an easy way to split up your code to make it both more reusable and more maintainable.
You can just as easily put an entire application in one big honking source file but you may find that the file will get rather big, leading to the compiler complaining about it (or at least taking a long time to compile it).
Typically you would hive off a part of your application (such as a generic database access layer) into a separate source file such as
db.cppand create adb.hfile with its API. This file isn’t so much used bydb.cppas it is used by all the other files that need to call the functions indb.cpp. It can be included indb.cppbut it tends to be mostly published information about thedbcode.As to how an environment figures out which things to compile/link: you tend to have a project of some sort (makefile, IDE project file, etc) which lists all the programs that you want to compile (usually not header files).
The environment will compile each source file that it has been told about to produce an object file – part of this process is incorporating the included header files into each source file, to make a compilation or translation unit – this unit is basically the source file with the included header files incorporated at the point where the
#includewas.The environment will then link all the object files to form an executable. Keep in mind there are variations on this process such as late (dynamic) linking. See here for a description of this.