I use a static library in the c++ program. Can memory stores multiple copies of the library? Or for one program, one copy of a static library?
Asked
Active
Viewed 722 times
2
-
A library is essentially an indexed sequence of object files. The linker will extract the object files it needs to satisfy dependencies of the program, but not more. The linker glues these object files from the library together with the object files the compiler generated from your source files into one executable. When you run that, parts of that executable may at any given point in time in memory (in particular when the program flow or data access touches a part, of course) or not, like with any program. Each executable will contain its own copy of a given object file from a given library. – Peter - Reinstate Monica Feb 07 '17 at 10:53
-
The C++ standard says nothing about use of libraries, static or otherwise (the standard library is something different). The answer to your question will depend on your operating system, not the programming language. Tagging your question C++ therefore makes it off-topic. – Peter Feb 07 '17 at 10:54
-
1Are you using DLLs on Windows or Shared Objects on Posix? If not, there will be one copy of the library. If you are using DLLs on Windows which are linked with the static library, each DLL will have it's own copy. If you link to .so files on Posix then each .so will have its own copy *but they will all use one copy* (picked by the program loader). If you load .so files via `dlload` on Posix, I'm not quite sure what happens. – Martin Bonner supports Monica Feb 07 '17 at 10:58
-
@MartinBonner this is all true but OP seems to be asking something rather different. – n. m. could be an AI Feb 07 '17 at 11:04
1 Answers
6
I use a static library in the c++ program
No you don't.
You are using a static library while linking a program, but a finished program contains no trace of the library as a separate entity. There are zero copies of the library in your program.
Your program contains copies of (some of) the object files that live in the static library. Once picked up by the linker, they are on equal standing with all other (non-shared) object files you use (e.g. the one that contains the main
function). Having two copies of any of them would be like having two copies of main
.

n. m. could be an AI
- 112,515
- 14
- 128
- 243
-
can you please tell me for example if i am calling printf function 5 times then 5 definitions are copied to the executable when statically linked? – RaHuL Jul 28 '21 at 17:00
-
1You missed the key ue-code... build an EXE and a dozen DLL's - that all reference a common static library, and all include code from an .obj file from that static library... – David V. Corbin May 23 '23 at 18:50