Sign in Join
Wiki copytemporary

Lazarus/FPC Libraries: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11This page describes the possibilities for creating libraries with Lazarus/FPC and using them in projects and packages.
22
33## Related Topics
44
55- [[Creating bindings for C libraries]] - How to convert C header files (.h) to pascal units
66
77## General
88
99### Static linking
1010
1111FPC compiles and links a static executable by default. That means it tells the linker to put all .o files of the project and all packages into one big executable.
1212
1313- Advantages:
1414 - No external dependencies.
1515- Disadvantages:
1616 - No code is shared between different programs on the same computer.
1717 - You can not load/unload a plugin.
1818
1919### Dynamic libraries
2020
2121The alternative to static linking is using dynamic libraries. The idea of dynamic libraries is to share code between programs,
2222
2323- Advantages:
2424 - Saving the memory of the code
2525 - Reducing startup time for often used libraries
2626 - Allowing plugins.
2727- Disadvantages:
2828 - They are slower for seldomly used libs.
2929 - Their structure and internals are more complicated (this is mainly a problem for the compiler).
3030 - Their initialization is different (see below)
3131 - Sharing code requires a version system to only mix compatible code.
3232
3333## Operating Systems
3434
3535| Operating System | Dynamic library extension | Static library extension | Library prefix |
3636|----|----|----|----|
3737| FreeBSD | .so | .a | lib |
3838| macOS | .dylib | .a | lib |
3939| Linux | .so | .a | lib |
4040| Windows | .dll | .lib | n/a |
4141| Haiku | .so | .a | lib |
4242
4343The library prefix and extension columns indicate how the names of libraries are resolved and created for the listed operating systems.
4444
4545### FreeBSD
4646
4747To Do.
4848
4949### macOS
5050
5151Under macOS, the library name will always have the lib prefix when it is created. So if you create a dynamic library called test, this will result in the file `libtest.dylib`. When importing routines from shared libraries, it is not necessary to give the library prefix or the library filename extension.
5252
5353Before [[User Changes 2.2.2|FPC 2.2.2]] released in August 2008, 32 bit .dylibs required exported symbols to be prefixed with an underscore. This is no longer the case.
5454
5555The standard locations for dynamic libraries are `~/lib`, `/usr/local/lib`, and `/usr/lib`. Starting with macOS 10.15 (Catalina) `/usr/lib` is on the system read-only volume so cannot be used for third-party libraries. While you may also place the .dylib file in a non-standard location in your file system, you then must add that location to one of these environment variables:
5656
5757- LD_LIBRARY_PATH
5858- DYLD_LIBRARY_PATH
5959- DYLD_FALLBACK_LIBRARY_PATH
6060
6161Private shared libraries should be included in your application's [[Application Bundle]]. This is especially important for libraries which do not have a stable ABI (eg OpenSSL) so that they are revision-locked to the application and cannot be superseded by any other, even newer, versions that may be available to the operating system.
6262
6363Refer to the See also section below for additional macOS information.
6464
6565### Linux
6666
6767A dynamic library filename always has the form 'lib'+packagename+'.so'+version. For example: `libz.so.1` and `libz.so.1.2.2`.
6868
6969Linux searches a library in this order:
7070
7171- first in the paths of the environment variable `LD_LIBRARY_PATH`
7272- then in /lib
7373- then /usr/lib
7474- finally the paths of `/etc/ld.so.conf`
7575
7676Using `ldconfig` after copying your library file into a lib directory may help with caching issues.
7777
7878To share memory (`GetMem`/`FreeMem`, strings) with other libraries (not written in FPC) under Linux, you should use the **unit cmem**. This unit must be added as **the very first unit** in the uses section of the project main source file (typically .lpr), so that its initialization section is called before any other unit can allocate memory.
7979
8080### Windows
8181
8282Windows searches a library in:
8383
8484- first in the current directory
8585- then the system directory
8686- finally the directories specified in the environment variable PATH (system and user path).
8787
8888*to do: wasn't there a change in Vista+ behaviour for this?*
8989
9090When using an FPC made DLL with a non-FPC host application, exception handling can lead to some problems. Workarounds are mentioned in the #Initialization section.
9191
9292## ppumove, .ppu, .ppl
9393
9494FPC normally creates for every unit a .ppu and .o file. The **.ppu file** contains every important information of the .pas/.pp file (types, required filenames like the .o file), while the **.o file** contains the assembler code and the mangled names understood by the current system.
9595
9696The **ppumove** tool included with every FPC installation, converts one or several .ppu and .o files into a dynamic library. It does this by calling the linker to gather all .o files into a .so (windows: .dll) file and removes the .o filename references from the .ppu file. These new .ppu files are normally called **.ppl files**.
9797
9898For example:
9999
100100You have the output directory of a package (where the .ppu files are):
101101
102102``` bash
103103ppumove -o packagename -e ppl *.ppu
104104```
105105
106106This will convert all .ppu files into .ppl files and creates a libpackagename.so (windows: packagename.dll). Note that under Linux the prefix 'lib' is always prepended.
107107
108108This new library can already be used by other programming languages like C. Or by FPC programs by using the **external** modifiers. But the initialization/finalization sections must be called automatically. This includes the initialization/finalization of the heap manager. This means no strings or GetMem. Of course FPC programmers are spoiled and they can get more.
109109
110110## External - statically loading a dynamic library
111111
112112The static loading of a dynamic library can be done in code, by using the external keyword, like in the example below which shows how a gtk function is loaded:
113113
114114``` pascal
115115const
116116{$ifdef win32}
117117 gtklib = 'libgtk-win32-2.0-0.dll';
118118{$else}
119119 {$ifdef darwin}
120120 gtklib = 'gtk-x11-2.0';
121121 {$linklib gtk-x11-2.0}
122122 {$else}
123123 gtklib = 'libgtk-x11-2.0.so';
124124 {$endif}
125125{$endif}
126126
127127procedure gtk_widget_set_events(widget:PGtkWidget; events:gint); cdecl; external gtklib;
128128```
129129
130130## Loadlibrary - dynamically loading a dynamic library
131131
132132Loading a dynamic library is simple with the Loadlibrary function of the unit dynlibs.
133133
134134The main problem is to get the filename, which depends on the version and the operating system. Since 2.2.2, a constant "sharedsuffix" is declared in unit dynlibs to ease this. It maps to the relevant extension (dll/so/dylib) without a point as prefix.
135135
136136Here are the functions declared in the unit dynlibs:
137137
138138``` pascal
139139Function SafeLoadLibrary(Name : AnsiString) : TLibHandle;
140140Function LoadLibrary(Name : AnsiString) : TLibHandle;
141141Function GetProcedureAddress(Lib : TlibHandle; ProcName : AnsiString) : Pointer;
142142Function UnloadLibrary(Lib : TLibHandle) : Boolean;
143143```
144144
145145SafeLoadLibrary is the same as LoadLibrary but it also disables arithmetic exceptions which some libraries expect to be off on loading.
146146
147147Pseudocode of the usage:
148148
149149``` pascal
150150uses dynlibs;
151151
152152var
153153 MyLibC: TLibHandle;
154154 MyProc: TMyProc;
155155begin
156156 MyLibC := LoadLibrary('libc.' + SharedSuffix);
157157 if MyLibC = 0 then Exit;
158158 MyProc := TMyProc(GetProcedureAddress(MyLibC, 'getpt');
159159 if MyProc = nil then Exit;
160160end;
161161```
162162
163163Pseoudocode for using a function, taking parameters:
164164
165165``` pascal
166166uses ...dynlibs...
167167
168168procedure UseDLL;
169169type
170170 TMyFunc=function (aInt:Integer; aStr: string):String; StdCall;
171171var
172172 MyLibC: TLibHandle= dynlibs.NilHandle;
173173 MyFunc: TMyFunc;
174174 FuncResult: string;
175175begin
176176 MyLibC := LoadLibrary('libc.' + SharedSuffix);
177177 if MyLibC = dynlibs.NilHandle then Exit; //DLL was not loaded successfully
178178 MyFunc:= TMyFunc(GetProcedureAddress(MyLibC, 'MyFunc');
179179 FuncResult:= MyFunc (5,'Test'); //Executes the function
180180 if MyLibC <> DynLibs.NilHandle then if FreeLibrary(MyLibC) then MyLibC:= DynLibs.NilHandle; //Unload the lib, if already loaded
181181end;
182182```
183183
184184> **Note:** Before 1.9.4, the unit dl was used for this. Since 1.9.4, dynlibs provides a portable alternative. Note that pretty much any use of unit dl that can't be substituted by using dynlibs is typically already unportable amongst Unices. This alone makes it advisable to use unit dynlibs as much as possible.
185185
186186### Simplified overview of the system, when loading a shared library under Linux
187187
188-<img src="lazarus_free_pascal_libraries_loading_under_linux.png" title="Loading a shared library..." width="350" alt="Loading a shared library..." />\
188+![Loading a shared library...](/wiki-images/a/ad/Lazarus_free_pascal_libraries_loading_under_linux.png)\
189189This chart summarizes how to configure a shared library (referenced by its soname, and its real-name, at least) in /etc/ld.so.conf and to update the library cache using *ldconfig* utility, to inform the Linux system library loader named *ldd* (other methods to load a shared library, with an environment variable like LD_LIBRARY_PATH, with code, by inclusion in the binary elf, etc, are also illustrated in the chart). For information, it's often necessary to check if a soft-symlink exists between the soname and the real-name, at least. The installation of development packages (*-dev*.deb files, for a Debian installation) always delivers such soft-symlink (ex.: abc.so) pointing to the soname (ex.: abc.so.{9}) on which the development package depends. Release packages sometimes forget this, whereas they are best placed to retrieve and to make point an old installation towards a new installed real-name library: indeed, shared libraries should respect the takeover of precedence in their existing APIs, features, at least inside the same soname (backward compatibility).
190190
191191## Creating a library
192192
193193See the Free Pascal Documentation: <http://www.freepascal.org/docs-html/prog/progse55.html>
194194
195195## Initialization
196196
197197Every unit can contain an initialization section. The order of the initialization sections depend on the uses sections of each unit.
198198
199199The initialization of the RTL itself (in system.pp) that is done before your initialization sections are entered slightly differs between a program and a shared library. Most notably there is a difference in how the exception handling is initialized:
200200
201201### Exception handling
202202
203203#### Windows
204204
205205On Windows systems it has been [reported](http://bugs.freepascal.org/view.php?id=12974) that there is no exception handler installed to catch hardware exceptions like access violations or floating point errors; all other native Pascal exceptions that are raised with Raise will work however.
206206
207207If you really need to catch these hardware exceptions you have to install your own handler, on Windows (beginning with versions XP and later) this is conveniently possible with AddVectoredExceptionHandler() and RemoveVectoredExceptionHandler(), there are some code examples in the above mentioned bug report. Note: work has been started in FPC 2.7.1/trunk to address this problem using 32 bit SEH.
208208
209209#### UNIX and UNIX-like systems
210210
211211On UNIX and UNIX-like systems (BSD, Darwin, Linux etc) no exception handler is installed to catch hardware exceptions (signals) like access violations in shared libraries. If you wish to catch these exceptions (signals) in a library code, you need to explicitly call `HookSignal(RTL_SIGDEFAULT)` during library initialization and call `UnhookSignal(RTL_SIGDEFAULT)` during finalization.
212212
213213Keep in mind that when you enable signal handling in your shared library, it will replace signal handlers installed by a host application or other shared libraries of the current process. It may cause unexpected behavior. It is known that Java on Linux uses the SIGSEGV signal for its internal functionality and will crash if a third-party JNI library overrides the SIGSEGV signal handler.
214214
215215### FPU mask
216216
217217For Delphi compatibility reasons, Free Pascal on i386 will [unmask](http://bugs.freepascal.org/view.php?id=16801) all FPU exceptions in the floating point unit (but without installing a handler for the dll, see above). This unmasking is done before your initialization section begins. If your DLL will be used with a host application that is made with a different compiler (almost all other compilers except FPC and Delphi/ C++ Builder *please verify C++ builder*) this will badly interfere with the host application's exception handling.
218218
219219After the LoadLibrary() call, the host application won't be able to catch any floating point exceptions anymore. The FPU will suddenly have gained the ability to throw hardware exceptions (in the thread that called LoadLibrary()), and the host application will most likely not expect this to happen and not be able to handle it properly. The workaround is to put
220220
221221``` pascal
222222Set8087CW(Get8087CW or $3f);
223223```
224224
225225in the initialization section to mask them again for the thread that loaded the library. This won't have any unwanted side effects other than restoring what the host application had all the time. In your DLL you would not have been able to catch them anyway (at least not on Windows, see above). If you really need to catch zero-divide and related errors in a DLL that is written for a non-FPC application, you have to
226226
227227- have a handler installed like mentioned above
228228- temporarily unmask the FPU before the try
229229- mask it again before you return to the host application
230230
231231## Finalization
232232
233233Every unit can contain a finalization section. The order is the reverse order of the initialization sections.
234234
235235After all finalization sections are executed it will call the procedure that you have previously assigned to Dll_Process_Detach_Hook.
236236
237237Be very careful what you do in this procedure:
238238
239239- all other units will already be finalized
240240- parts of the RTL might not work as expected anymore
241241- creating and freeing objects on the heap or even using Pascal strings inside this procedure is a sure way to call for trouble.
242242
243243If you have to stop threads and free objects you must find a way to do this before the library unloading - it is too late to do it here.
244244
245245## Versions, Distribution
246246
247247Libraries tend to grow and change over time. Adding new features is no problem, but removing a public method or changing its parameters makes the library incompatible. That means either an installed library (.so, .dll, .dylib) is replaced by a compatible one **or** a new library must be added to the system. That's why every library contains a version.
248248
249249To do: explain how to set/use this version both on Windows and *nix
250250
251251To load a dynamic library (**dlopen** of **unit dynlibs**) the correct filename must be known. Under Linux this means that you have to know the version number.
252252
253253To do: proposal how the IDE should create version numbers
254254
255255## See also
256256
257257- [[macOS Programming Tips|macOS Programming Tips - Libraries]]
258258- [[macOS Dynamic Libraries]]
259259- [[macOS Static Libraries]]
260260- FPC [[shared library]]
261261- FPC [[packages]]
262262- [[Translations / i18n / localizations for programs]]
263263
264264---
265265*From the Free Pascal wiki, page "Lazarus/FPC Libraries", as it stood on 2021-09-24 after a change by Eric69, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history