C++ How to include class headers without having to compile their cpp files?

We can include < iostream > and we do not care about its cpp file, but why can't we do the same for our own classes ?

So if my project uses 50 custom classes, not only do I have to have 50 includes, but also have to compile/link 50 cpp files along with them (and clutter the project tree).

Q: Is there any way to use custom headers the same way we use standard libraries ?

In other words is there a kosher way so that we do not have to add all those cpp files in the project. I want to only include ClassSnake.hpp which in turn knows where to find ClassSnake.cpp which links to ClassVector.hpp which knows how to find ClassVector.cpp ... all in an automatic daisy chain without me having to explicitly add those cpp files in my project tree.

Edit: I am not worried so much about the cpp files recompiling. My issue is with having to remember which class internally links to which other class, so that I can properly include all those hidden cpp files in the project tree ... and clutter the tree.

在这里输入图像描述


Not really.

What you're missing is that your compiler toolchain has already compiled the bits <iostream> needs that aren't in the header.

Your compiler (linker really) just implicitly links this code in without you having to specify it.

If you want to clean up your project tree a bit, you could create other projects that are libraries of code for one main project to use.


Headers do not (normally) provide implementations of things (functions, classes), they must be implemented somewhere if you are going to use them.

When you include your own header, you include your own sources in order to provide the implementation. Straight forward enough there.

When you include a standard header (such as iostream), the implementation is in the libraries you include (either implicitly because the compiler just does it, or explicitly through compiler/linker options).


As an extention to Collin's answer, you could always offload "shared" code to a shared library, and then reference the header files and lib files in your other projects. The lib files will only come in to play at the linker stage, as all those other pesky .cpp files have already been compiled.

If this is is just a self-enclosed project with no other commonality, you're just going to have to suck up the fact you have to provide an implementation :)

链接地址: http://www.djcxy.com/p/64198.html

上一篇: 将头文件包含在.h文件中但不包含在.cpp文件中时出错

下一篇: C ++如何包含类头文件而不必编译它们的cpp文件?