• Places
    • Home
    • Graphs
    • Prefixes
  • Admin
    • Users
    • Settings
    • Plugins
    • Statistics
  • Repository
    • Load local file
    • Load from HTTP
    • Load from library
    • Remove triples
    • Clear repository
    • RDF quality heuristics
  • Query
    • YASGUI SPARQL Editor
    • Simple Form
    • SWISH Prolog shell
  • Help
    • Documentation
    • Tutorial
    • Roadmap
    • HTTP Services
  • Login

12.5 Linking embedded applications using swipl-ld
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
      • Foreign Language Interface
        • Linking embedded applications using swipl-ld
          • A simple example
    • Packages

12.5.1 A simple example

The following is a very simple example going through all the steps outlined above. It provides an arithmetic expression evaluator. We will call the application calc and define it in the files calc.c and calc.pl. The Prolog file is simple:

calc(Atom) :-
        term_to_atom(Expr, Atom),
        A is Expr,
        write(A),
        nl.

The C part of the application parses the command line options, initialises the Prolog engine, locates the calc/1 predicate and calls it. The coder is in figure 8.

#include <stdio.h>
#include <string.h>
#include <SWI-Prolog.h>

#define MAXLINE 1024

int
main(int argc, char **argv)
{ char expression[MAXLINE];
  char *e = expression;
  char *program = argv[0];
  char *plav[2];
  int n;

  /* combine all the arguments in a single string */

  for(n=1; n<argc; n++)
  { if ( n != 1 )
      *e++ = ' ';
    strcpy(e, argv[n]);
    e += strlen(e);
  }

  /* make the argument vector for Prolog */

  plav[0] = program;
  plav[1] = NULL;

  /* initialise Prolog */

  if ( !PL_initialise(1, plav) )
    PL_halt(1);

  /* Lookup calc/1 and make the arguments and call */

  { predicate_t pred = PL_predicate("calc", 1, "user");
    term_t h0 = PL_new_term_refs(1);
    int rval;

    PL_put_atom_chars(h0, expression);
    rval = PL_call_predicate(NULL, PL_Q_NORMAL, pred, h0);

    PL_halt(rval ? 0 : 1);
  }

  return 0;
}
Figure 8 : C source for the calc application

The application is now created using the command line below. The option -goal true sets the Prolog initialization goal to suppress the banner. Note that the -o calc does not specify an extension. If the platform uses a file extension for executables, swipl-ld will add this (e.g., .exe on Windows).

% swipl-ld -goal true -o calc calc.c calc.pl

The created program calc is a native executable with the Prolog code attached to it. Note that the program typically depends on the shared object libswipl and, depending on the platform and configuration, on several external shared objects.

% ./calc pi/2
1.5708

ClioPatria (version V3.1.1-40-g9d9e003)