Q&A

  1. How can I ensure files are compiled with certain Nim compiler flags?
  2. How can I ensure files are compiled with certain underlying compiler flags?

How can I ensure files are compiled with certain compiler flags?

Consider this humble Nim program, named "hello.nim":

when defined(dosomething):
  echo "hello"

By default, a command like nim r hello will result in silence from this program.

But if you add this neighbor to the file, named "hello.nims" (note final s, for NimScript):

switch("define", "dosomething")

Then nim r hello will have some new output:

Hint: used config file '/path/to/file/hello.nims' [Conf]
...
hello

Now, suppose you add a third file named "another.nim":

import hello
when defined(dosomething):
  echo "another"

With this file, nim r another will greet you again with silence. "hello.nims" is not considered by the imported module, nor does it apply to the differently-named "another.nim".

Another way to add flags is with a "nim.cfg" file, which doesn't contain NimScript:

-d:dosomething
-d:anotherthing

With this new neighbor, nim r another will have some new output:

Hint: used config file '/path/to/file/nim.cfg' [Conf]
...
hello
another

A particularly useful use of nim.cfg is adding a project's source code to the path of its tests:

--path:"../src"

How can I ensure files are compiled with certain underlying compiler flags?

For that, there's the passC pragma. The related pragmas are also very useful. A fun example is a compile pragma in nim-lang/zip that casually adds 5000 lines of C code to a build.