Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 36 ยท Getting Started

Hello, Nim: Compile and Run

Write and compile your first Nim program, learn nim c -r, release builds, backends, comments, echo, reading input and command-line arguments, with C stand-ins.

Time to write real Nim. In this lesson you create a file, compile it, run it, and learn the handful of compiler options you will use every day. You also see how a program prints text, reads input and receives command-line arguments.

The Nim code below is read-only because the Nim compiler is not available on this site. The C blocks are runnable stand-ins that show the same behavior.

Your first program

Create a file called hello.nim:

NIM
echo "Hello, Nim!"

That is the whole program. There is no main function and no import: top-level statements run in order, and echo is always available because it lives in the system module, which every file imports automatically.

Compile and run it in one step:

Terminal
nim c -r hello.nim

c means "compile with the C backend" and -r means "run the result afterwards". The output is:

TEXT
Hello, Nim!

Without -r, you get an executable named hello (or hello.exe on Windows) next to the source, which you run yourself.

The compiler command

The general form is nim <command> [options] <file>.

Command What it does
nim c Compile with the C backend (the usual choice)
nim cpp Compile via C++
nim js Compile to JavaScript
nim check Type-check only; fast feedback, no executable
nim doc Generate HTML documentation from doc comments

Useful options:

Option Meaning
-r / --run Run the program after compiling
-d:release Optimized build with checks kept (good default for shipping)
-d:danger Optimized build with runtime checks removed (fastest, least safe)
--opt:size / --opt:speed Choose the optimizer goal
--outdir:bin Put the executable in a folder
-o:name Choose the output name
--hints:off Hide hint messages

A plain nim c builds in debug mode: slower code with checks for overflow, bounds and nil, plus stack traces. Use -d:release before you measure speed.

Comments

NIM
# A line comment

#[ A block comment,
   can span lines ]#

## A documentation comment: nim doc turns this into HTML.
echo "comments are ignored"

Block comments can be nested, so you can comment out code that already contains block comments.

echo and strings

echo takes any number of arguments, converts each to text with $, joins them without spaces and ends with a newline:

NIM
echo "Total: ", 3 + 4, " items"
echo "pi is about ", 3.14159

Strings are written in double quotes. A raw string uses r"..." (no escapes), and """...""" is a multi-line string. The output of the first line above is Total: 7 items.

To print without a trailing newline use stdout.write:

NIM
stdout.write "Enter your name: "
let name = readLine(stdin)
echo "Hello, ", name, "!"

readLine(stdin) reads one line from standard input. When input ends, it raises an EOFError; use stdin.readLine in a loop with try or check endOfFile(stdin) for batch input.

Command-line arguments

The os module exposes the arguments:

NIM
import std/os

echo "Program: ", getAppFilename()
echo "Arguments: ", paramCount()
for i in 1 .. paramCount():
  echo i, ": ", paramStr(i)

If you run ./hello one two, paramCount() is 2, paramStr(1) is one, and commandLineParams() gives you the arguments as a seq[string]. Unlike C, paramStr(0) is the program name and the count does not include it.

For serious tools use the parseopt module or a package such as cligen (see the tooling chapter).

A stand-in for arguments and input

In C, main receives argc and argv, and argv[0] is the program name. This runnable C stand-in mimics the Nim program above: it prints each argument, and reads names from standard input, which you can edit in the Input box.

C Stand-in: arguments and a greeting loop in C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In the page runner there are no command-line arguments, so the first line shows 0; the two names in the Input box produce two greetings. The idea carries over: the runtime gives your program text, and you process it.

Exit codes

A Nim program ends with exit code 0 when the last statement finishes. Use quit(1) (or quit(QuitFailure)) to stop early with an error code, which shells and build systems read:

NIM
if paramCount() < 1:
  echo "usage: hello NAME"
  quit(1)

An uncaught exception also ends the program with a non-zero code and, in debug builds, a stack trace.

A second stand-in: exit codes

C Stand-in: exit code decides success

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The page prints the status line; the program then returns a failure code, which is what quit(1) does in Nim.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does nim c -r hello.nim do?

    c selects the C backend and -r runs the executable after a successful build.
  2. 2. Which flag gives an optimized build that keeps runtime checks?

    -d:release optimizes but keeps checks; -d:danger also removes them.
  3. 3. Does a Nim program need a main function?

    A file's top-level statements are the program; there is no required main.
  4. 4. In Nim, what is paramStr(0)?

    paramStr(0) is the program itself; arguments start at 1, and paramCount() does not count the program.

Summary

  • A Nim program is a file of statements; echo "Hello" is a complete program.
  • nim c -r file.nim compiles and runs; -d:release makes an optimized build; nim check only type-checks.
  • Comments: #, #[ ... ]# and ## for documentation.
  • readLine(stdin) reads input; paramStr/paramCount read arguments; quit(code) sets the exit status.

Next: Variables: let, var and const