- program that processes its input data to produce output that is used as input to another program
In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers. The amount and kind of processing done depends on the nature of the preprocessor; some preprocessors are only capable of performing relatively simple textual substitutions and macro expansions, while others have the power of fully-fledged programming languages.
A common example from computer programming is the processing performed on source code before the next step of compilation. In some computer languages (e.g., C) there is a phase of translation known as preprocessing.
Lexical pre-processorsLexical preprocessors are the lowest-level of preprocessors, insofar as they only require lexical analysis, that is, they operate on the source text, prior to any parsing, by performing simple substitution of tokenized character sequences for other tokenized character sequences, according to user-defined rules. They typically perform macro substitution, textual inclusion of other files, and conditional compilation or inclusion.
Pre-processing in C/C++The most widely used lexical preprocessor is CPP, the C preprocessor, used pervasively in C and its descendant, C++. This preprocessor is used to provide the usual set of preprocessing services
InclusionThe most common use of the C preprocessor is the
- include "..."
While this use of a preprocessor for code reuse is simple, it is also slow, rather inefficient and requires the additional use of conditional compilation to avoid multiple inclusions of a given header file.
Since the 1970s, faster, safer and more efficient alternatives to reuse by file inclusion have been known and used by the programming language community, and implemented in most programming languages: Java and Common Lisp have packages, Pascal has units, Modula, OCaml, Haskell and Python have modules, and D, designed as a replacement of C and C++, has imports.
MacrosMacros are commonly used in C to define small snippets of code. During the preprocessing phase, each macro call is replaced, in-line, by the corresponding macro definition. If the macro has parameters, they are substituted into the macro body during expansion; thus, a C macro can mimic a C function. The usual reason for doing this is to avoid the overhead of a function call in simple cases, where the code is lightweight enough that function call overhead has a significant impact on performance.
For instance, #define max(a,b) a > b ? a : b defines the macro max, taking two arguments a and b. This macro may be called like any C function, using identical syntax. Therefore, after preprocessing, z = max(x,y); becomes z = x > y ? x : y ; While this use of macros is very important for C, for instance to define type-safe generic data-types or debugging tools, it is also slow, rather inefficient, and may lead to a number of pitfalls.
For instance, if f and g are two functions, calling z = max(f(), g()); will not evaluate f()once and g() once, and place the highest value in z as one may believe. Rather, one of the functions will be evaluated twice. If that function has side effects, this is usually not the expected behavior.
C macros are capable of mimicking functions, creating new syntax within some limitations, as well as expanding into arbitrary text (although the C compiler will require that text to be valid C source code, or else comments), but they have some limitations as a programming construct. Macros which mimic functions, for instance, can be called like real functions, but a macro cannot be passed to another function using a function pointer, since the macro itself has no address.
More modern languages typically do not use this form of metaprogramming through macro expansion of character strings, rather relying on either automatic or manual inlining of functions and methods, and other abstraction techniques such as templates, generic functions, or parametric polymorphism. In particular, inline functions overcome one of the major disadvantages of macros in modern C and C++ implementations, since an inline function provides the macro's advantage of avoiding the overhead of a function call, while its address can still be stored in a function pointer for indirect calls or use in parameters. Also, the problem of multiple evaluation, seen above in the max macro, would not occur in an inlined function.
Conditional compilationThe C preprocessor also offers conditional compilation. This permits having different versions of a same code in the same source file. Typically, this is used to customize the program with respect to the compilation platform, the status (debugging code can be "defined out" in production code), as well as to ensure that header files are only included once.
In this common case, the programmer will use a construct like this:
- ifndef FOO_H
- define FOO_H
This "macro guard" protects the header file from duplicate inclusion by testing for the existence of a macro which, by convention, has the same name as the header file itself. The definition of the FOO_H macro takes place when the header file is first processed by CPP. Thereafter, if that header file is included again, FOO_H will already be defined, causing the preprocessor to skip the entirety of the header file's text.
Preprocessor conditionals can be used in more complex ways, as below:
- ifdef x
- if x
This technique is often used in system header files to test for various features whose definition can change depending on the platform; for example, the GNU C Library uses "feature-test" macros to ensure that operating system and hardware differences are properly handled, while maintaining the same portable interface.
Once again, most modern programming languages discard this feature, rather relying on traditional if...then...else... flow control operators, leaving to the compiler the task of removing useless code from the executable.
Other lexical pre-processorsOther lexical preprocessors include the general-purpose m4, most commonly used in cross-platform build systems such as autoconf, and GEMA, an open source macro processor which operates on patterns of context.
Syntactic pre-processorsSyntactic preprocessors were introduced with the Lisp family of languages. Their role is to transform syntax trees according to a number of user-defined rules. For some programming languages, the rules are written in the same language as the program (compile-time reflection). This is the case with Lisp and OCaml. Some other languages rely on a fully external language to define the transformations, such as the XSLT preprocessor for XML, or its statically typed counterpart CDuce.
Syntactic preprocessors are typically used to customize the syntax of a language, extend a language by adding new primitives, or embed a Domain-Specific Programming Language inside a general purpose language.
Customizing syntaxA good example of syntax customization is the existence of two different syntaxes in the Objective Caml programming language. Programs may be written indifferently using the "normal syntax" or the "revised syntax", and may be pretty-printed with either syntax on demand.
Similarly, a number of programs written in OCaml customize the syntax of the language by the addition of new operators.
Extending a languageThe best examples of language extension through macros are found in the Lisp family of languages. While the languages, by themselves, are simple dynamically-typed functional cores, the standard distributions of Scheme or Common Lisp permit imperative or object-oriented programming, as well as static typing. Almost all of these features are implemented by syntactic preprocessing, although it bears noting that the "macro expansion" phase of compilation is handled by the compiler in Lisp. This can still be considered a form of preprocessing, since it takes place before other phases of compilation.
Similarly, statically-checked, type-safe regular expressions or code generation may be added to the syntax and semantics of OCaml through macros, as well as micro-threads (also known as coroutines or fibers), monads or transparent XML manipulation.
Specializing a languageOne of the unusual features of the Lisp family of languages is the possibility of using macros to create an internal Domain-Specific Programming Language. Typically, in a large Lisp-based project, a module may be written in a variety of such minilanguages, one perhaps using a SQL-based dialect of Lisp, another written in a dialect specialized for GUIs or pretty-printing, etc. Common Lisp's standard library contains an example of this level of syntactic abstraction in the form of the LOOP macro, which implements an Algol-like minilanguage to describe complex iteration, while still enabling the use of standard Lisp operators.
The MetaOCaml preprocessor/language provides similar features for external Domain-Specific Programming Languages. This preprocessor takes the description of the semantics of a language (i.e. an interpreter) and, by combining compile-time interpretation and code generation, turns that definition into a compiler to the OCaml programming language -- and from that language, either to bytecode or to native code.`
General purpose preprocessorMost preprocessors are specific to a particular data processing task (e.g., compiling the C language). A preprocessor may be promoted as being general purpose, meaning that it is not aimed at a specific usage or programming language, and is intended to be used for a wide variety of text processing tasks.
M4 is probably the most well known example of such a general purpose preprocessor, although the C preprocessor is sometimes used in a non-C specific role. Examples:
- using M4 (see on-article example) or C preprocessor as a template engine, to HTML generation.
- imake, a make interface using the C preprocessor, used in the X Window System but now deprecated in favour of automake.
- grompp, a preprocessor for simulation input files for GROMACS (a fast, free, open-source code for some problems in computational chemistry which calls the system C preprocessor (or other preprocessor as determined by the simulation input file) to parse the topology, using mostly the #define and #include mechanisms to determine the effective topology at grompp run time.
preprocessor in Czech: Preprocesor
preprocessor in Danish: Præprocessor
preprocessor in German: Präprozessor
preprocessor in Persian: پیشپردازنده
preprocessor in French: Préprocesseur
preprocessor in Italian: Preprocessore
preprocessor in Lithuanian: Preprocesorius
preprocessor in Dutch: Preprocessor
preprocessor in Japanese: プリプロセッサ
preprocessor in Polish: Preprocesor
preprocessor in Portuguese: Pré-processador
preprocessor in Russian: Препроцессор
preprocessor in Ukrainian: Препроцесор