Building "Monolithic" Libraries
I have a series of small library "modules" designed to handle very specific tasks. A single module usually consists of just a .h
and a .cpp
, and possibly another set to provide relevant non-friend, non-member functions that the user might find useful.
For example, Foo.h
might declare a class called Foo
, that Foo.cpp
defines, and FooUtilities.h
might declare a function that uses Foo
which is defined by FooUtilities.cpp
.
Normally to use these modules in my programs, I add the .h
and .cpp
to my project and #include
the .h
in whatever files need it. However, for larger programs that use more potentially-interdependent modules, this is growing to be a big inconvenience. Therefore, I'd like to compile it all as a single mono开发者_StackOverflowlithic static or dynamic library so I can just add the library file to my project, set the header search directories to folders that contain the aforementioned .h
files, and compile.
Seems pretty simple, right? All I'd have to do is start a new project with a static/dynamic library as its build target and then add all the appropriate files. The .cpp
files, which #include
the .h
files anyway, will be compiled and added to the final product.
However, some of the modules use templates and therefore have to use .tpp
instead of .cpp
. The .tpp
files are only meant for organization and are #include
d by their respective header files, which is the opposite of how the normal modules are handled. Because of this, just adding them to my library project won't compile anything.
How can I work around this? Should I have a CompileThis.cpp
file that includes all the modules that use templates? If so, should this file also include the non-template modules? It seems like this could rapidly become an organizational mess.
Many compilers cannot "precompile" templates into libraries. My best suggestion is to treat them like header files; header files are not compiled into libraries, they are just included.
I compile code into a library when the amount of changes is minimal. This often speeds up the build process since those files don't need to be compiled again (and again...).
Should I have a CompileThis.cpp file that includes all the modules that use templates?
Yes - you'll still need an object to link. It's also nice because it will perform the syntax/instantiation checks (assuming your depends are properly ordered).
If so, should this file also include the non-template modules?
that depends on the structure.
at minimum, it should include/define what it must export (and their dependencies).
it should often include the headers represented by the module, in order to easily detect errors issues at the package level.
ideally, you'll add all necessary concepts and some instantiations (in some cases).
this makes it easier to maintain, and will not require major restructuring when you realize you have moved from needing 0 exported symbols to needing one or more.
精彩评论