How to explicitly control exported symbols of dynamic shared libraries
Benefits of exporting symbols on demand
- Reduce the amount of time of loading the library.
- Reduce the size of library.
- Optimize the code generation.
- Improve library maintainability and make the library easier to use.
- Reduce the potential for symbol collision.
List the symbols of shared library
1. nm
https://llvm.org/docs/CommandGuide/llvm-nm.html
nm -gD libxxx.so
2. objdump
https://llvm.org/docs/CommandGuide/llvm-objdump.html
objdump -T libxxx.so
3. readelf
https://man7.org/linux/man-pages/man1/readelf.1.html
readelf -Ws libxxx.so
Option 1. the visibility attribute
1 |
Compile the code with -fvisibility=hidden
flag. This option forces the default visibility of all symbols to be hidden
.
1 | c++ -I. -fvisibility=hidden -o a.o -c a.cpp |
On Windows, using the keyword __declspec(dllexport) to export symbols . See https://learn.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-declspec-dllexport?view=msvc-170
See more details: https://gcc.gnu.org/wiki/Visibility