Preprocessor#
The Vala preprocessor is a particular part of Vala that acts at syntax level only, allowing you to conditionally write pieces of your software depending upon certain compile-time conditions. Preprocessor directives will never be generated in the resulting code.
Directives syntax#
All preprocessor directives start with a hash (#), except for the first line of a file starting with #! (used for Vala scripts).
vala-code:[ any vala code ] [ pp-condition ] [ any vala code ]pp-condition:#if pp-expression vala-code [ pp-elif ] [ pp-else ] #endifpp-elif:#elif pp-expression vala-code [ pp-elif ]pp-else:#else vala-codepp-expression:pp-or-expressionpp-or-expression:pp-and-expression [ || pp-and-expression ]pp-and-expression:pp-binary-expression [ && pp-binary-expression ]pp-binary-expression:pp-equality-expressionpp-inequality-expressionpp-equality-expression:pp-unary-expression [ == pp-unary-expression ]pp-inequality-expression:pp-unary-expression [ != pp-unary-expression ]pp-unary-expression:pp-negation-expressionpp-primary-expressionpp-negation-expression:! pp-unary-expressionpp-primary-expression:pp-symbol( pp-expression )truefalsepp-symbol:identifier
The semantics of the preprocessor are very simple: if the condition is true then the Vala code surrounded by the preprocessor will be parsed, otherwise it will be ignored. A symbol evaluates to true if it is defined at compile-time. If a symbol in a preprocessor directive is not defined, it evaluates to false.
Defining symbols#
It’s not possible to define a preprocessor symbol inside the Vala code
(like with C). The only way to define a symbol is to feed it through the
valac
option -D
.
Built-in defines#
Name |
Description |
---|---|
|
Set if the profile is posix |
|
Set if the profile is gobject |
|
Set if Vala API version is equal or higher to version X.Y |
Examples#
How to conditionally compile code based on a valac
option -D
.
Sample code:
vala-test:examples/advanced.vala
1// Vala preprocessor example
2public class Preprocessor : Object {
3
4 /* public instance method */
5 public void run () {
6#if PREPROCESSOR_DEBUG
7 // Use "-D PREPROCESSOR_DEBUG" to run this code path
8 stdout.printf ("debug version");
9#else
10 // Normally, we run this code path
11 stdout.printf ("production version");
12#endif
13 }
14}
15
16/* application entry point */
17void main () {
18 var sample = new Preprocessor ();
19 sample.run ();
20}
Compile and Run#
Normal build/run:
$ valac -o preprocessor Preprocessor.vala
$ ./preprocessor
Debug build/run:
$ valac -D PREPROCESSOR_DEBUG -o preprocessor-debug Preprocessor.vala
$ ./preprocessor-debug