## 10.2 Runtimes and Foreign Code

Some applications may need to use the foreign language interface. Object code is by definition machine-dependent and thus cannot be part of the saved program file.

To complicate the matter even further there are various ways of loading foreign code:

- Using the library(shlib) predicates
  This is the preferred way of dealing with foreign code. It loads quickly and ensures an acceptable level of independence between the versions of the emulator and the foreign code loaded. It works on Unix machines supporting shared libraries and library functions to load them. Most modern Unixes, as well as Win32 (Windows 95/NT), satisfy this constraint.
- Static linking
  This mechanism works on all machines, but generally requires the same C compiler and linker to be used for the external code as is used to build SWI-Prolog itself.

To make a runtime executable that can run on multiple platforms one must make runtime checks to find the correct way of linking. Suppose we have a source file `myextension.c` defining the installation function install().

If this file is compiled into a shared library, load_foreign_library/1 will load this library and call the installation function to initialise the foreign code. If it is loaded as a static extension, define install() as the predicate install/0 :

    static foreign_t
    pl_install()
    { install();

      PL_succeed;
    }

    PL_extension PL_extensions [] =
    {
    /*{ "name",     arity,  function,       PL_FA_<flags> },*/

      { "install",  0,      pl_install,     0 },
      { NULL,       0,      NULL,           0 } /* terminating line */
    };

Now, use the following Prolog code to load the foreign library:

    load_foreign_extensions :-
            current_predicate(install, install), !, % static loaded
            install.
    load_foreign_extensions :-                      % shared library
            load_foreign_library(foreign(myextension)).

    :- initialization load_foreign_extensions.

The path alias `foreign` is defined by file_search_path/2. By default it searches the directories `<home>/lib/<arch>` and `<home>/lib`. The application can specify additional rules for file_search_path/2.