Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Library headers and compiling?

I'm unclear about what gets included into the final program when a compiler reads the #include or import directives of various function or class libraries.

Does the entire library get inserted into the program, or does the compiler read in only the functions or classes that appear in the source code? It would seem like a lot of wasted memory if the entire library is included when only a single function or class was needed.

1 Answer

Relevance
  • 9 years ago
    Favorite Answer

    It depends a bit on which language you are talking about, but in general a #include or import directive doesn't bring any code into the program. It only tells the compiler that certain bits of code exist in a library. If some of those bits of code are then referenced in your code, then, yeah, they will be brought into your code, in one form or another.

    Functions you do reference from a #include or import may bring in a bunch of code from a library file, or they may just reference a specific function in a DLL file. So it can be hard to know exactly how much baggage you are bringing in.

    But let's look at a worst case scenario. You reference 1 function that takes 1000 bytes for the actual code. But it brings in a whole library that is 100K. Have you wasted 99K of *memory*? Probably not. There might be 100K of *virtual* memory allocated to that library. So it consumes a chunk of address *space*. But virtual memory is ultra cheap. When your code actually tries to execute the code in that 1K of the library that you need, then that code will get paged in from virtual memory to physical memory. At that point, you will use 1 page worth of physical memory. A page is typically 4K or 8K of memory. So that 1 K library function might waste 3K or 7K of memory. But that is a lot better than wasting 100K, no?

    In general, today, it doesn't pay to worry about it to much. Unless you are working in an embedded system or some other scenario where every byte still counts. Virtual memory makes it much harder to compute the real memory cost of an application. But it also makes it much less important to do so than it used to be.

Still have questions? Get your answers by asking now.