Блог радиста
Блог о Linux в частности и Open Source в общем, о программировании и немного о M$ Windows
Статические и динамические библиотеки в Linux
Статические и динамические библиотеки в Linux
Сегодня мы поговорим о библиотеках в Linux (подозреваю также, что многие описанные здесь вещи возможны и в других *nix-операционных системах, но это требует проверки 🙂 ).
1) Статические библиотеки (создание с помощью Assembler, C/C++; подключение и использование в программах на Assembler,C/C++);
2) Динамические библиотеки (создание с помощью Assembler, C/C++; подключение и использование в программах на C/C++l, Python).
1) Статическая библиотека — это такая библиотека, которая связывается (линкуется) с программой в момент компиляции оной. При этом объектный код библиотеки помещается в исполняемый файл программы. С этой точки зрения статическая библиотека похожа на исходный код программы, с которой она связывается, за исключением того, что библиотека компилируется «кем-то еще» и программист, использующий библиотеку, имеет дело исключительно только с результатом этой компиляции.
В Linux, как правило, файл-статическая_библиотека имеет расширение «.a»
2) Статические библиотеки на языке C.
Исходный код библиотеки:
Сохраните его в файле static.c
Ключевое слово extern необходимо для того, чтобы функция была видна в программе.
Теперь скомпилируем (! без линковки) библиотеку:
gcc -c static.c -o static.o
(на выходе имеем файл static.o, содержащий объектный код нашей библиотеки)
ar rc libMY_STATIC.a static.o
ar упаковывает несколько (! Это важно. Дело не ограничивается только одним объектным файлом) объектных файлов в одну статическую библиотеку. Статическая библиотека имеет расширение «.a», при этом ее название должно начинаться с «lib» (дань традиции).
Параметры ar:
r — предписывает заменять старые версии объектных файлов новыми — необходим для переупаковки библиотеки;
c — создать статическую библиотеку, если та еще не существует.
Проиндексируем функции внутри библиотеки для более быстрой линковки:
Итак, мы получили статическую библиотеку libMY_STATIC.a.
Теперь попытаемся использовать библиотеку в нашей программе:
Исходный текст программы (C):
Сохраните его в файле program1.c
Способы связывания библиотеки и программы:
— Скомпилируем и слинкуем (в том числе с нашей библиотекой) нашу программу:
gcc program1.c libMY_STATIC.a
(предполагается, что в качестве аргумента gcc будут переданы полные пути (!) к вашим библиотекам)
На выходе получим:
Hello world! I’m static library
Return code: 0
— Скомпилируйте с помощью команды:
gcc program1.c -L. -lMY_STATIC -o a1.out
— путь к каталогу, содержащему наши библиотек (используйте «-L
— название нашей библиотеки (это важно — название (!), а не имя файла — собственно, если библиотека имеет своим именем «libBLABLABLA.a», то ее названием будет «BLABLABLA» — т.е. имя без приставки «lib» и расширения «.a») (для нескольких библиотек используйте «-l -l . «)
Запустите файл a1.out на выполнение и удостовертесь, что результаты те же, что и в предыдущем пункте.
— Видоизменим предыдущий способ — уберем аргументы «-L»:
В начале проверим значение переменной LD_LIBRARY_PATH и содержимое файла /etc/ld.so.conf:
echo $LD_LIBRARY_PATH ; cat /etc/ld.so.conf
На экране появился некоторый список каталогов — это те каталоги, в которых система ищет библиотеки при их линковке с программой (еще к таким каталогам относятся:
/lib
/usr/lib
. Поместите libMY_STATIC.a в один из этих каталогов:
(Я, к примеру, засуну нашу библиотеку в каталог /usr/lib):
su -c ‘cp libMY_STATIC.a /usr/lib’
(в Ubuntu — sudo cp libMY_STATIC.a /usr/lib )
ldconfig
(ldconfig обновляет кеш данных о библиотеках линковщика)
Теперь скомпилируем и запустим нашу программу:
gcc program1.c -lMY_STATIC -o a2.out
./a2.out
Hello world! I’m static library
Return code: 0
Бинго! Кстати, таким вот способом вы можете подключать к своей программе любые статические библиотеки из приведенных выше каталогов.
* Бывает полезно определить все прототипы функций библиотеки в некотором заголовочном файле, который будет потом включаться в вашу программу. Это не обязательно, но удобно.
3) Статические библиотеки на языке Assembler.
Представьте, что вам необходимо оптимизировать выполнение некоторых действий в вашей программе. Разумеется, вы может применить ключевое слово asm (если пишите программу на C/C++), но лучшим решением будет создание оптимизированной вами библиотеки на языке Assembler и подключение ее к вашей программе. Давайте попробуем:
*Кстати, углубляться в процесс компиляции библиотеки и ее линковки с вашей программой я не буду (!). Этот процесс идентичен полностью (!) тому же процессу для библиотек, написанных на языке C.
Итак, имеем вот такую программу:
Сохраните ее в файле program2.c
Скомпилируйте ее и запустите:
Я привел этот пример, чтобы показать действительно возможность оптимизации программы с помощью библиотеки на Assembler’е. Вы можете заметить, что вызов printf в main() не оптимален, т.к. printf, по крайней мере, один раз использует цикл while для поиска вхождений конструкций «%. » в строку. Это не оптимально, т.к. очевидно, что таковых символов у нас нет. Оптимизируем нашу программу с помощью библиотеки на Assebmler’е:
my_printf:
movl $4,%eax
xorl %ebx,%ebx
incl %ebx
movl $hw,%ecx
movl $hw_e,%edx
int $0x80
xorl %eax,%eax
ret
Сохраните исходный код библиотеки в файле static2.s
Это AT&T наречие Assembler’а.
.globl my_printf — «my_printf» описывается как глобальная (видимая в других объектных файлах) последовательность
my_printf: — начало описание функции my_printf
movl $4,%eax — поместим 4 в eax (4 — номер системного вызова write)
xorl %ebx,%ebx и incl %ebx — поместим в ebx единицу — номер STDOUT
movl $message,%ecx — в ecx запишем адрес начала сообщения
movl $message_l,%edx — в edx поместим адрес конца сообщения
int $0x80 — произведем системный вызов write
xorl %eax,%eax — в eax — код возврата (0)
ret — вернемся в вызывающую процедуру
.data — секция данных (разумеется, мы могли бы передавать выводимую строку как параметр, но тогда вычисление ее конца потребовало бы от нас дополнительных усилий, что, согласитесь, лениво 🙂 )
Теперь получим библиотеку:
gcc -c static2.s -o static2.o
ar rc static2.a static2.o
ranlib static2.a
На выходе имеем статическую библиотеку static2.a
Теперь напишем программу, использующую эту статическую библиотеку (язык C):
Сохраните текст программы в файле program3.c
Заметьте, я добавил прототип библиотечной функции для удобства.
Скомпилируем и слинкуем программу с библиотекой, после чего запустим программу на выполнение:
gcc program3.c static2.a
./a.out
На выходе получим:
* Принцип линкования статических библиотек с программами на Assembler’е аналогичен принципу для программ на C. Просто, когда будете использовать статические библиотеки в Assembler’е, помните о соглашениях C по передаче аргументов в функцию и возвращению результата.
4) Статические библиотеки на языке C++.
Принцип создания аналогичен статическим библиотекам на C, но перед каждой экспортируемой функцией не забывайте добавлять:
(экспортировать как функцию на C — т.е. без расширения имен).
* Кстати, используйте g++ вместо gcc, если захотите протестировать приведенные выше примеры.
Подключение к вашей программе аналогично подключению к программе, написанной на C, за исключением необходимости явно добавлять к тексту программы прототипы импортируемых функций в следующем виде:
extern «C» PROTOTYPE
Где PROTOTYPE — прототип импортируемой функции.
* При подключении статических библиотек на C++ к программе на C сопряжено с некоторыми трудностями — т.к. при компиляции и линковки программы необходимо будет также вручную подключить системные библиотеки для реализации функционала, предоставляемого библиотекой Standart C++ сверх того, что предоставляет библиотека Standart C.
Динамические библиотеки (shared).
1) Динамическая библиотека — библиотека, подключаемая к программе в момент выполнения. Это означает, что при создании библиотеки производится не только ее компиляция, но и линковка с другими, нужными ей, библиотеками (!).
Динамические библиотеки полезны в случаях, если:
— Важно не перекомпилировать всю программу, а только перекомпилировать ту часть, которая реализует определенные функции — тогда эти функции выносятся в динамическую библиотеку;
— Важно использовать в программах на C библиотеки, подготовленные на C++ и при этом избежать лишних трудностей с линковкой программы;
— Кроме того, динамические библиотеки позволяют экономить место на жестком диске и в оперативной памяти, если одна и таже библиотека используется несколькими программами.
В Linux, обычно, динамические библиотеки имеют расширение «.so».
2) Подготовим исходный код динамической библиотеки (пример на C++).
Исходный код динамической библиотеки по принципам создания ничем (!) не отличается от исходного кода статических библиотек.
Здесь мы подготовим некоторый пример, который в дальнейшем будем использовать повсеместно во всей части 2.
Итак, исходный код библиотеки (C++):
extern «C» int hello()
<
cout 3) Компиляция и линковка динамических библиотек.
Давайте получим динамическую библиотеку:
Получим файл с объектным кодом:
g++ -fPIC -c dynamic.cpp -o dynamic.o
(используйте gcc для программ на С и Assembler’е)
-fPIC — использовать относительную адресацию в переходах подпрограмм — во избежание конфликтов при динамическом связывании
А теперь из объектного файла получим библиотеку:
g++ -shared -olibdynamic.so dynamic.o
(используйте gcc для программ на С и Assembler’е)
libdynamic.so — имя результирующей библиотеки;
-shared — предписывает создать динамическую (т.е. «разделяемую») библиотеку.
* Именуйте динамические библиотеки следующим способом:
Итак, на выходе мы имеем libdynamic.so — нашу динамическую библиотеку.
4) Использование динамической библиотеки в программе на C/C++.
— Связывание с библиотекой во время компиляции программы (C/C++):
—— Подготовим исходный код нашей программы:
Сохраните его в файле Dprogram1.c
extern «C» int hello();
Сохраните его в файле Dprogram1.cpp
(единственное отличие, как вы можете заметить, в ключевом слове extern — см. часть 1 пункт 4)
—— Теперь добьемся того, чтобы система смогла найти нашу библиотеку. Поместим libdynamic.so в один из каталогов:
cat /etc/ld.so.conf
и выполните потом » ldconfig «
—— И, наконец, скомпилируем программу и слинкуем ее с библиотекой:
gcc ИСХОДНИК -lИМЯ_БИБЛИОТЕКИ -o РЕЗУЛЬТИРУЮЩИЙ_БИНАРИК
В нашем случае: gcc Dprogram1.c -L/home/amv/c/libs/ -ldynamic
(используйте g++ для программы на C++)
Запустим на исполнение полученный файл:
В итоге должно получится:
— Связывание с библиотекой во время исполнения программы (C/C++):
Разумеется, предыдущий пример неплох. Однако бывает необходимо подключать библиотеку во время выполнения программы. Для этого можно использовать функционал из заголовочного файла .
Исходный код примера (C):
int main()
<
void *handle = dlopen(«libdynamic.so»,RTLD_LAZY);
int(*fun)(void) = dlsym(handle,»hello»);
int x = (*fun)();
dlclose(handle);
printf(«Return code: %d\n»,x);
return 0;
>;
######################
Сохраните его в файле Dprogram2.c
В dlfcn.h определены следующие функции:
void* dlopen(«PATH_AND_NAME»,FLAG) — загружает в память динамическую библиотеку с полным именем PATH_AND_NAME и возвращает ее описатель (HANDLE) (NULL в случае неудачи). FLAG — флаги, описанные в «man dlopen»;
void* dlsym(HANDLE,»NAME») — возвращает указатель на функцию/переменную, импортируемую из библиотеки;
int dlclose(HANDLE) — выгружает библиотеку из памяти;
const char *dlerror() — получить сообщение о последней возникшей ошибке (NULL — если ошибок не произошло с момента последнего вызова dlerror).
* Посмотрите на досуге вот этот перевод «man dlopen»: Привет, OpenNET
gcc -ldl Dprogram2.c
(используйте g++ для программы на C++)
Запустим на исполнение полученный файл:
В итоге должно получится:
* Важно! Нет необходимости помещать библиотеку в один из специальных каталогов, модифицировать переменные окружения и выполнять «ldconfig»
— Использование динамической библиотеки в программе на Python:
Все предельно просто.
—— Поместим libdynamic.so в один из каталогов:
cat /etc/ld.so.conf
и выполните потом «ldconfig»
Исходный текст программы на python’е:
Модуль ctypes входит в стандартную поставку модулей python версии 2.5 и выше.
Фуф. Мы проделали довольно большую работу, но ведь это только верхушка айсберга.
Источник
Static, Shared Dynamic and Loadable Linux Libraries
This tutorial discusses the philosophy behind libraries and the creation and use of C/C++ library «shared components» and «plug-ins». The various technologies and methodologies used and insight to their appropriate application, is also discussed. In this tutorial, all libraries are created using the GNU Linux compiler.
Related YoLinux Tutorials:
Libraries employ a software design also known as «shared components» or «archive libraries», which groups together multiple compiled object code files into a single file known as a library. Typically C functions/C++ classes and methods which can be shared by more than one application are broken out of the application’s source code, compiled and bundled into a library. The C standard libraries and C++ STL are examples of shared components which can be linked with your code. The benefit is that each and every object file need not be stated when linking because the developer can reference the library collective. This simplifies the multiple use and sharing of software components between applications. It also allows application vendors a way to simply release an API to interface with an application. Components which are large can be created for dynamic use, thus the library can remain separate from the executable reducing it’s size and thus less disk space is used for the application. The library components are then called by various applications for use when needed.
Benefits include:
- Component reuse: update one library, shared resource takes up less disk space.
- Version management: Linux libraries can cohabitate old and new versions on a single system.
- Component Specialization: niche and specialized developers can focus on their core competency on a single library. Simplifies testing and verification.
There are two Linux C/C++ library types which can be created:
- Static libraries (.a): Library of object code which is linked with, and becomes part of the application.
- Dynamically linked shared object libraries (.so): There is only one form of this library but it can be used in two ways.
- Dynamically linked at run time. The libraries must be available during compile/link phase. The shared objects are not included into the executable component but are tied to the execution.
- Dynamically loaded/unloaded and linked during execution (i.e. browser plug-in) using the dynamic linking loader system functions.
Library naming conventions:
Consider the following compile and link command: gcc src-file.c -lm -lpthread
The libraries referenced in this example for inclusion during linking are the math library («m») and the thread library («pthread»). They are found in /usr/lib/libm.a and /usr/lib/libpthread.a.
Note: The GNU compiler now has the command line option «-pthread» while older versions of the compiler specify the pthread library explicitly with «-lpthread». Thus now you are more likely to see gcc src-file.c -lm -pthread
How to generate a static library (object code archive file):
- Compile: cc -Wall -c ctest1.c ctest2.c
Compiler options:- -Wall: include warnings. See man page for warnings specified.
- Create library «libctest.a»: ar -cvq libctest.a ctest1.o ctest2.o
- List files in library: ar -t libctest.a
- Linking with the library:
- cc -o executable-name prog.c libctest.a
- cc -o executable-name prog.c -L/path/to/library-directory -lctest
- Example files:
- ctest1.c
- ctest2.c
- prog.c
Historical note: After creating the library it was once necessary to run the command: ranlib ctest.a. This created a symbol table within the archive. Ranlib is now embedded into the «ar» command.
Note for MS/Windows developers: The Linux/Unix «.a» library is conceptually the same as the Visual C++ static «.lib» libraries.
How to generate a shared object: (Dynamically linked object library file.) Note that this is a two step process.
- Create object code
- Create library
- Optional: create default version using a symbolic link.
Library creation example: This creates the library libctest.so.1.0 and symbolic links to it.
It is also valid to cascade the linkage: If you look at the libraries in /lib/ and /usr/lib/ you will find both methodologies present. Linux developers are not consistent. What is important is that the symbolic links eventually point to an actual library.
- -Wall: include warnings. See man page for warnings specified.
- -fPIC: Compiler directive to output position independent code, a characteristic required by shared libraries. Also see «-fpic».
- -shared: Produce a shared object which can then be linked with other objects to form an executable.
- -Wl,options: Pass options to linker.
In this example the options to be passed on to the linker are: «-soname libctest.so.1«. The name passed with the «-o» option is passed to gcc. - Option -o: Output of operation. In this case the name of the shared object to be output will be «libctest.so.1.0«
- The link to /opt/lib/libctest.so allows the naming convention for the compile flag -lctest to work.
- The link to /opt/lib/libctest.so.1 allows the run time binding to work. See dependency below.
Compile main program and link with shared object library:
Compiling for run-time linking with a dynamically linked libctest.so.1.0: Use: Where the name of the library is libctest.so. (This is why you must create the symbolic links or you will get the error «/usr/bin/ld: cannot find -lctest».)
The libraries will NOT be included in the executable but will be dynamically linked during run-time execution.
The shared library dependencies of the executable can be listed with the command: ldd name-of-executable
Example: ldd prog [Potential Pitfall] : Unresolved errors within a shared library may cause an error when the library is loaded. Example:
Error message at run-time:
The first three libraries show that there is a path resolution. The last two are problematic.
The fix is to resolve dependencies of the last two libraries when linking the library libname-of-lib.so:
- Add the unresolved library path in /etc/ld.so.conf.d/name-of-lib-x86_64.conf and/or /etc/ld.so.conf.d/name-of-lib-i686.conf
Reload the library cache (/etc/ld.so.cache) with the command: sudo ldconfig
or - Add library and path explicitly to the compiler/linker command: -lname-of-lib -L/path/to/lib
or - Add the library path to the environment variable to fix run-time dependency:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/lib
- Set path: export LD_LIBRARY_PATH=/opt/lib:$LD_LIBRARY_PATH
- Run: prog
Example with code:
Using the example code above for ctest1.c, ctest2.c and prog.c
- Compile the library functions: gcc -Wall -fPIC -c ctest1.c ctest2.c
- Generate the shared library: gcc -shared -Wl,-soname,libctest.so.1 -o libctest.so.1.0 ctest1.o ctest2.o
This generates the library libctest.so.1.0 - Move to lib/ directory:
- sudo mv libctest.so.1.0 /opt/lib
- sudo ln -sf /opt/lib/libctest.so.1.0 /opt/lib/libctest.so.1
- sudo ln -sf /opt/lib/libctest.so.1 /opt/lib/libctest.so
Compile program for use with a shared library: gcc -Wall -L/opt/lib prog.c -lctest -o prog
[Potential Pitfall] : If the symbolic links are not created (above), you will get the following error: The reference to the library name -lctest refers to /opt/lib/libctest.so - Configure the library path (see below and choose one of three mechanisms).
In this example we set the environment variable: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/lib - Run the program: ./prog
[Potential Pitfall] : You get the following error if the library path is not set:
- gcc — GNU C compiler
- ld — The GNU Linker
- ldd — List library dependencies
- ldconfig — configure dynamic linker run time bindings (update cache /etc/ld.so.cache)
In order for an executable to find the required libraries to link with during run time, one must configure the system so that the libraries can be found. Methods available: (Do at least one of the following)
- Add library directories to be included during dynamic linking to the file /etc/ld.so.conf
Add the library path to this file and then execute the command (as root) ldconfig to configure the linker run-time bindings.
You can use the «-f file-name» flag to reference another configuration file if you are developing for different environments.
See man page for command ldconfig.
Add specified directory to library cache: (as root)
ldconfig -n /opt/lib
Where /opt/lib is the directory containing your library libctest.so
(When developing and just adding your current directory: ldconfig -n . Link with -L.)
This will NOT permanently configure the system to include this directory. The information will be lost upon system reboot.
Specify the environment variable LD_LIBRARY_PATH to point to the directory paths containing the shared object library. This will specify to the run time loader that the library paths will be used during execution to resolve dependencies.
(Linux/Solaris: LD_LIBRARY_PATH, SGI: LD_LIBRARYN32_PATH, AIX: LIBPATH, Mac OS X: DYLD_LIBRARY_PATH, HP-UX: SHLIB_PATH)
Example (bash shell): export LD_LIBRARY_PATH=/opt/lib:$LD_LIBRARY_PATH or add to your
This instructs the run time loader to look in the path described by the environment variable LD_LIBRARY_PATH, to resolve shared libraries. This will include the path /opt/lib.
Library paths used should conform to the «Linux Standard Base» directory structure.
ar: list object files in archive library
This will list all of the object files held in the archive library: Also see: Man page for ar
nm: list symbols: object files, archive library and shared library
The command «nm» lists symbols contained in object files:
The command «nm» lists symbols contained in the archive library:
Object symbols in static archive libraries are categorized using the source and object file hierarchy of the library:
The command «nm» lists symbols contained in the object file or shared library.
Use the command nm -D libctest.so.1.0
(or nm --dynamic libctest.so.1.0)
Note that other platforms (Cygwin) may not respond to «-D». Try nm -gC libctest.so.1.0
Also see: Man page for nm
Symbol Type | Description |
---|---|
A | The symbol’s value is absolute, and will not be changed by further linking. |
B | Un-initialized data section |
D | Initialized data section |
T | Normal code section |
U | Undefined symbol used but not defined. Dependency on another library. |
W | Doubly defined symbol. If found, allow definition in another library to resolve dependency. |
Also see: objdump man page
readelf: list symbols in shared library
The command «readelf» command to list symbols contained in a shared library:
Use the command readelf -s /usr/lib64/libjpeg.so
Also see: readelf man page
Library versions should be specified for shared objects if the function interfaces are expected to change (C++ public/protected class definitions), more or fewer functions are included in the library, the function prototype changes (return data type (int, const int, . ) or argument list changes) or data type changes (object definitions: class data members, inheritance, virtual functions, . ).
The library version can be specified when the shared object library is created. If the library is expected to be updated, then a library version should be specified. This is especially important for shared object libraries which are dynamically linked. This also avoids the Microsoft «DLL hell» problem of conflicting libraries where a system upgrade which changes a standard library breaks an older application expecting an older version of the the shared object function.
Versioning occurs with the GNU C/C++ libraries as well. This often make binaries compiled with one version of the GNU tools incompatible with binaries compiled with other versions unless those versions also reside on the system. Multiple versions of the same library can reside on the same system due to versioning. The version of the library is included in the symbol name so the linker knows which version to link with.
One can look at the symbol version used: nm csub1.o
No version is specified in object code by default.
There is one GNU C/C++ compiler flag that explicitly deals with symbol versioning. Specify the version script to use at compile time with the flag: --version-script=your-version-script-file
Note: This is only useful when creating shared libraries. It is assumed that the programmer knows which libraries to link with when static linking. Run-time linking allows opportunity for library incompatibility.
GNU/Linux, see examples of version scripts here: sysdeps/unix/sysv/linux/Versions
Some symbols may also get version strings from assembler code which appears in glibc headers files. Look at include/libc-symbols.h.
Example: nm /lib/libc.so.6 | more
Note the use of a version script.
Library referencing a versioned library: nm /lib/libutil-2.2.5.so
These libraries are dynamically loaded / unloaded and linked during execution. Useful for creating a «plug-in» architecture.
Prototype include file for the library: ctest.h
Load and unload the library libctest.so (created above), dynamically:
gcc -rdynamic -o progdl progdl.c -ldl
- dlopen("/opt/lib/libctest.so", RTLD_LAZY);
Open shared library named «libctest.so«.
The second argument indicates the binding. See include file dlfcn.h.
Returns NULL if it fails.
Options:- RTLD_LAZY: If specified, Linux is not concerned about unresolved symbols until they are referenced.
- RTLD_NOW: All unresolved symbols resolved when dlopen() is called.
- RTLD_GLOBAL: Make symbol libraries visible.
- dlsym(lib_handle, "ctest1");
Returns address to the function which has been loaded with the shared library..
Returns NULL if it fails.
Note: When using C++ functions, first use nm to find the «mangled» symbol name or use the extern "C" construct to avoid name mangling.
i.e. extern "C" void function-name();
Object code location: Object code archive libraries can be located with either the executable or the loadable library. Object code routines used by both should not be duplicated in each. This is especially true for code which use static variables such as singleton classes. A static variable is global and thus can only be represented once. Including it twice will provide unexpected results. The programmer can specify that specific object code be linked with the executable by using linker commands which are passed on by the compiler.
Use the «-Wl» gcc/g++ compiler flag to pass command line arguments on to the GNU «ld» linker.
Example makefile statement: g++ -rdynamic -o appexe $(OBJ) $(LINKFLAGS) -Wl,--whole-archive -L
- —whole-archive: This linker directive specifies that the libraries listed following this directive (in this case AA_libs) shall be included in the resulting output even though there may not be any calls requiring its presence. This option is used to specify libraries which the loadable libraries will require at run time.
- -no-whole-archive: This needs to be specified whether you list additional object files or not. The gcc/g++ compiler will add its own list of archive libraries and you would not want all the object code in the archive library linked in if not needed. It toggles the behavior back to normal for the rest of the archive libraries.
- dlopen() — gain access to an executable object file
- dclose() — close a dlopen object
- dlsym() — obtain the address of a symbol from a dlopen object
- dlvsym() — Programming interface to dynamic linking loader.
- dlerror() — get diagnostic information
C++ and name mangling:
When running the above «C» examples with the «C++» compiler one will quickly find that «C++» function names get mangled and thus will not work unless the function definitions are protected with extern "C"<>.
Note that the following are not equivalent:
The following are equivalent:
Dynamic loading of C++ classes:
The dynamic library loading routines enable the programmer to load «C» functions. In C++ we would like to load class member functions. In fact the entire class may be in the library and we may want to load and have access to the entire object and all of its member functions. Do this by passing a «C» class factory function which instantiates the class.
The class «.h» file:
The class «.cpp» file:
Main executable which calls the loadable libraries:
Pitfalls:
- The new/delete of the C++ class should both be provided by the executable or the library but not split. This is so that there is no surprise if one overloads new/delete in one or the other.
The Microsoft Windows equivalent to the Linux / Unix shared object («.so») is the «.dll». The Microsoft Windows DLL file usually has the extension «.dll», but may also use the extension «.ocx». On the old 16 bit windows, the dynamically linked libraries were also named with the «.exe» suffix. «Executing» the DLL will load it into memory.
The Visual C++ .NET IDE wizard will create a DLL framework through the GUI, and generates a «.def» file. This «module definition file» lists the functions to be exported. When exporting C++ functions, the C++ mangled names are used. Using the Visual C++ compiler to generate a «.map» file will allow you to discover the C++ mangled name to use in the «.def» file. The «SECTIONS» label in the «.def» file will define the portions which are «shared». Unfortunately the generation of DLLs are tightly coupled to the Microsoft IDE, so much so that I would not recommend trying to create one without it.
The Microsoft Windows C++ equivalent functions to libdl are the following functions:
- ::LoadLibrary() — dlopen()
- ::GetProcAddress() — dlsym()
- ::FreeLibrary() — dlclose()
[Potential Pitfall] : Microsoft Visual C++ .NET compilers do not allow the linking control that the GNU linker «ld» allows (i.e. —whole-archive, -no-whole-archive). All symbols need to be resolved by the VC++ compiler for both the loadable library and the application executable individually and thus it can cause duplication of libraries when the library is loaded. This is especially bad when using static variables (i.e. used in singleton patterns) as you will get two memory locations for the static variable, one used by the loadable library and the other used by the program executable. This breaks the whole static variable concept and the singleton pattern. Thus you can not use a static variable which is referenced by by both the loadable library and the application executable as they will be unique and different. To use a unique static variable, you must pass a pointer to that static variable to the other module so that each module (main executable and DLL library) can use the same instantiation. On MS/Windows you can use shared memory or a memory mapped file so that the main executable and DLL library can share a pointer to an address they both will use.
Cross platform (Linux and MS/Windows) C++ code snippet:
Источник