LEVIATHAN v962456e · 962456eee1

Metaprogramming

target:: — the compilation-target constants

target::os, target::arch and target::triple are compile-time strings that describe the platform being compiled for.

since 0.1.0-alpha.1linuxwindowswasm

Description

Three compile-time string constants live in the reserved namespace target:

Constant Value
target::os "linux", "windows", "macos", "wasm" or "unknown"
target::arch The first component of the target triple, normalized, so arm64 reads as aarch64
target::triple The exact --target string; a native build gets the canonical spelling of the host

They exist only at compile time. The usual use is to choose an import or a branch per platform (see the example below).

The program below tests the constants in ways whose answer does not depend on the host, so it prints the same on every platform:

The constants are always set

comptime bool osKnown = target::os == "linux" || target::os == "windows" || target::os == "macos" || target::os == "wasm";
comptime bool archKnown = target::arch != "";
comptime bool tripleKnown = target::triple != "";

console.writeln(osKnown);
console.writeln(archKnown);
console.writeln(tripleKnown);
true
true
true

The values themselves differ from host to host:

Printing the constants

comptime string os = target::os;
comptime string arch = target::arch;
comptime string triple = target::triple;
console.writeln("os=${os} arch=${arch} triple=${triple}");
not run — output depends on the build target

Rules

  • The values describe the target, not the machine that runs the compiler. Under --target <triple> the destination's branch folds; for example --target x86_64-pc-windows-gnu makes target::os read "windows" on a Linux build host.
  • The constants can be used only where a comptime value is allowed. In an ordinary run-time position there is no target symbol, and the use is an unresolved-name error.
  • A member that is not one of the three, such as target::bogus, is a compile error that lists the three constants.

Examples

Choosing an import per platform. Both namespaces define name, and the comptime if brings in only the one for the target:

Choosing an import per platform

namespace WinConsole { public string name() => "windows console"; }
namespace PosixConsole { public string name() => "posix console"; }

comptime if (target::os == "windows") {
    uses WinConsole;
} else {
    uses PosixConsole;
}

string who = name();
console.writeln(who.length() > 0);

Notes

  • For a target the compiler does not recognize, target::os is "unknown". Compare against the names you support instead of assuming one of the other four.

See also