4.3.1.2 Conditional compilation
Conditional compilation builds on the same principle as term_expansion/2, goal_expansion/2 and the expansion of grammar rules to compile sections of the source code conditionally. One of the reasons for introducing conditional compilation is to simplify writing portable code. See section C for more information. Here is a simple example:
:- if(\+source_exports(library(lists), suffix/2)). suffix(Suffix, List) :- append(_, Suffix, List). :- endif.
Note that these directives can only appear as separate terms in the
input. SWI-Prolog accomodates syntax extensions under conditional
compilation by silently ignoring syntax errors when in the
false branch. This allow, for example, for the code below. With
rational number support 1r3
denotes the rational number 1/3
while without it is a syntax error. Note that this only works properly
if (1) the syntax error still allows to re-synchronize on the full stop
of the invalid clause and (2) the subsequent conditional compilation
directive is valid.
:- if(current_prolog_flag(bounded, false)). one_third(1r3). :- endif.
Typical usage scenarios include:
- Load different libraries on different dialects.
- Define a predicate if it is missing as a system predicate.
- Realise totally different implementations for a particular part of the code due to different capabilities.
- Realise different configuration options for your software.
- :- if(:Goal)
- Compile subsequent code only if Goal succeeds. For enhanced portability, Goal is processed by expand_goal/2 before execution. If an error occurs, the error is printed and processing proceeds as if Goal has failed.
- :- elif(:Goal)
- Equivalent to
:- else. :-if(Goal).
...:- endif.
In a sequence as below, the section below the first matchingelif
is processed. If no test succeeds, the else branch is processed.:- if(test1). section_1. :- elif(test2). section_2. :- elif(test3). section_3. :- else. section_else. :- endif.
- :- else
- Start‘else’branch.
- :- endif
- End of conditional compilation.