Defining your own main()

Normally, when building an executable with qld the Quintus main() routine is linked in to the executable, which initializes the Prolog environment and calls QP_toplevel(). QP_toplevel() will either:

  1. Start an interactive top-level, which prompts for a command to be typed; or
  2. Call runtime(start) in the case of a runtime system (i.e. if -D was omitted in the call to qld).

However, you are not limited to using this default main(). You can define your main() and have Prolog as a function call.

This should be done if the Prolog component(s) of your application are such that they may not be called in a given run of the program. In that case, you would not want to initialize Prolog unless it became necessary.

An example of this sort of case is a program written in C that utilizes menus. The end user can select a number of options. One of these options involves further decision making, and runs an expert system written in Prolog. If the user doesn't happen to select this menu option on a given occasion, there is no reason to use the resources involved in initializing Prolog. So you would write a main() that is dependent upon this menu selection. Once the user selects this option and thus starts up Prolog, however, subsequent invocations will recognize that Prolog is already initialized and will not do it again.

Another situation where it makes sense to "redefine" main() is where you already have a large application written in C or some other foreign language and you wish to extend it with a module written in Prolog without having to rewrite the top level of the existing program.

If you choose to use a different main(), you should be aware that the default Quintus main() provides certain functionality, which will have to be included in the user-supplied main():

The built-in function QP_initialize() takes care of these tasks. An example of a user-supplied main() can be found in the reference page for QP_initialize().

The QP_* functions require that Prolog be initialized for memory management, etc. Thus, whenever main() is redefined, it will be necessary to call QP_initialize(). There is no harm in calling this routine more than once. So people writing portions of large projects can safely assume Prolog isn't initialized, and call QP_initialize().