This site has been retired. For up to date information, see handbook.gnome.org or gitlab.gnome.org.


[Home] [TitleIndex] [WordIndex

Back to Vala Reference Manual

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).

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

POSIX

Set if the profile is posix

GOBJECT

Set if the profile is gobject

DOVA

Set if the profile is dova

VALA_X_Y

Set if Vala API version is equal or higher to version X.Y

DBUS_GLIB

Set if using dbus-glib-1 package

Examples

How to conditionally compile code based on a valac option -D.

Sample code:

// Vala preprocessor example
public class Preprocessor : Object {

    public Preprocessor () {
    }

    /* public instance method */
    public void run () {
#if PREPROCESSOR_DEBUG
        // Use "-D PREPROCESSOR_DEBUG" to run this code path
        stdout.printf ("debug version \n");
#else
        // Normally, we run this code path
        stdout.printf ("production version \n");
#endif
    }

    /* application entry point */
    public static int main (string[] args) {
        var sample = new Preprocessor ();
        sample.run ();
        return 0;
    }
}

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

2024-10-23 11:37