Junior
What types of libraries do you know and what are their differences?
sobes.tech AI
Answer from AI
Types of libraries:
- Static libraries (.a in Linux, .lib in Windows): The library code is embedded directly into the application's executable during compilation. The application becomes larger in size but does not depend on the presence of the library itself at runtime. Each application using a static library has its own copy of the code.
- Dynamic (shared) libraries (.so in Linux, .dll in Windows): The library code is loaded into the application's memory at runtime. This reduces the size of the executable file. Multiple applications can use the same copy of the library, saving memory. For the application to work correctly, the dynamic library must be present in the system.
Main differences:
| Attribute | Static library | Dynamic library |
|---|---|---|
| Application size | Larger (code embedded) | Smaller (code loaded at runtime) |
| Dependency | None (code inside the executable) | Present (library must be in the system) |
| Memory usage | Each application has its own copy of the code | Multiple applications can share one copy |
| Code update | Requires recompilation of the application | Can update the library separately |
Example of using a static library in C++ (conditional):
// main.cpp
#include "static_library.h" // Header file of the static library
int main() {
// Call function from static library
static_function();
return 0;
}
Example of using a dynamic library in C++ (conditional):
// main.cpp
#include <dlfcn.h> // For functions to load dynamic libraries
int main() {
// Load dynamic library
void* handle = dlopen("dynamic_library.so", RTLD_LAZY);
if (!handle) {
// Error handling
}
// Get address of function from library
void (*dynamic_function)(void) = (void (*)(void))dlsym(handle, "dynamic_function");
if (!dynamic_function) {
// Error handling
}
// Call function
dynamic_function();
// Close library
dlclose(handle);
return 0;
}