Simple libraries often have more than one .c source file that gets compiled. Simple libraries are set up this way to conserve program memory. If each function in a given simple library resides in a different .c file, the application that uses the simple library will only get code for the functions it uses. If the simple library instead has one long, wandering .c file with a bunch of functions, the application will get the code for all the functions even if it only calls for one of them.
This tutorial builds on the How to Create a Simple Library tutorial, and shows how to split the single .c file into multiple .c files to save memory. It also demonstrates how a library can share global variables.
Let’s go back and try the test code from My Documents, and take some notes about the memory usage. We can use this as the “before” entry in a before/after comparison of how much memory a single function call to the awesome library takes.
Not much savings there! Removing the epic function call reduced the program size by four bytes. But, the code for the epic function is still in the program. The call to awesome brings in all the code from the .c source file where the .c function lives, even if it is not needed. Let’s restructure our library a little so that a call to the awesome function doesn’t bring in the code for both the awesome and epic functions.
Next, let's put the source code for the awesome function and epic function into separate .c source files. Then, you will be able to see a much larger program size difference when calling just one function instead of both.
Now, let’s move the epic function into a different file, and recompile.
Now that the library has been modified, a call to awesome should only add the awesome function code to the program size, not both the awesome and epic functions' code. Let’s test that.
Look how much memory was saved this time, the total code size dropped from 6,924 to 6,888 — a savings of 236 bytes! Much better than 4 bytes.
This activity illustrated the advantage to putting your awesome library's two functions into two separate c files. The more functions your library has, the more effective this strategy will be for saving code space.
However, you don't always need one .c file per function. If two or more functions always work together, there wouldn’t be any advantage to putting them in different files since the code for each of those would always be added to the total program size. Aside from that, if you have functions that can stand alone, you will benefit from putting them into separate files.