Multiple Source Files vs Libraries – C++ Project Management

clibraries

I write a lot of scientific software, and I originally got into programming with F77. I moved to C++ for my primary programming about 10 years ago now, but I do catch myself using F77 habits. One thing I cannot seem to get used to is library usage. To be clear, I understand why one would want to use one, but for most of the code I write, no one but the end user and the maintainers will ever use the routines I write, so I question the usefulness to me.

Okay, so libraries give you a good place to stash reusable code that's easy to follow and maintain. But didn't separate source files already solve that problem for my situation? What advantage would I gain by putting my source files into a library? I can understand executable file size savings with shared libraries, but is that all that important? I have a lot of math routines that are general and could be extracted to a shared library, but should I? Most of them are only called once by a single point in my code, and usually only by a single project, so do I gain anything? Isn't any memory savings gone the moment the symbol is resolved, and the code loaded? Thanks.

Best Answer

In your situation, you'd gain very little. In fact, you'd come up with a slight net loss as you now have a program and a library to maintain instead of just a program.

What you're really looking at is a question of where the object files for each of your sources end up, and maintaining them all in one place is perfectly acceptable until they need to be shared. The important thing is make sure your code is well-organized and modular so that when the time comes to share the general-purpose parts with a second project, making the split won't be a headache.

As executable size is concerned, code is code no matter where it comes from. Most modern operating systems demand page their executables and will share pages from the same binary across multiple copies running simultaneously. Code that gets used across many programs (e.g., the C library) makes sense to have in a shared library. For anything that's going to be used exactly once, it won't make a lot of difference whether it's in a static binary or one that links in shared libraries. (There's some additional overhead in dynamic versus static linking, but in general those hairs don't need to be split.)

Related Topic