2.16.3 Global terms, atoms, and functors
Sometimes it is convenient to put constant terms and atoms as global
variables in a file (with a static
qualifier), so that they
are only created (and looked up) cone. This is fine for atoms and
functors, which can be created by something like this:
static PlAtom ATOM_foo("foo"); static PlFunctor FUNCTOR_ff_2("ff", 2);
C++ makes no guarantees about the order of creating global variables
across “translation units” (that is, individual C++ files),
but the Prolog runtime ensures that the necessary initialization has
been done to allow PlAtom
and PlFunctor
objects to be created. However, to be safe, it is best to put such
global variables
inside functions - C++ will initialize them on their firstuse.
Global Terms need a bit of care. For one thing, terms are ephemeral,
so it is wrong to have a PlTerm
static variable - instead,
a
PlRecord
must be used, which will provide a fresh copy of
the term using PlRecord::term(). There is no guarantee that the
Prolog runtime has initialized everything needed for creating entries in
the recorded database (see
Recorded
database). Therefore, global recorded terms must be wrapped inside a
function. C++ will call the constructor upon first use. For example:
static PlTerm term_foo_bar() { static PlRecord r(PlCompound("foo", PlTermv(PlTerm_atom("bar"))).record()); return r.term(); }