Compile-Time Execution

26.1 const and static

The Nim VM runs most Nim code at compile time (no FFI or ptr arithmetic, limited I/O).

proc fib(n: int): int = (if n < 2: n else: fib(n - 1) + fib(n - 2))
const fib30 = fib(30)             # computed at compile time by the Nim VM
static:
  echo "This prints during compilation"
  doAssert fib(10) == 55

let lookup = static:              # build a table at compile time
  var t: array[256, uint8]
  for i in 0..255: t[i] = uint8(i * 2 mod 256)
  t

26.2 Compile-Time File and Command Access

const version = staticRead("VERSION").strip
const gitHash = staticExec("git rev-parse --short HEAD")
const buildDate = CompileDate & " " & CompileTime
const embeddedAsset = staticRead("assets/logo.svg")     # embed files in the binary

26.3 Conditional Compilation

Platform symbols: windows, linux, macosx, posix, bsd, android, ios, js, amd64, arm64, i386, wasm32.

when defined(release): echo "release"
when defined(myFeature): enableFeature()               # nim c -d:myFeature
const logLevel {.strdefine.} = "info"                  # nim c -d:logLevel=debug
const maxConn {.intdefine.} = 100
const useSsl {.booldefine.} = false
when compiles(someProc(1)): echo "someProc exists"
when declared(foo): echo "foo is declared"
when NimMajor >= 2: echo "Nim 2+"