Is it possible to `include` a file named dynamically, such as a variable name?

* * *

Normally no, because Nim is statically compiled. I found workaround with a 
macro and compile-time define pragma. Posting for future reference.

Add where the `include` statement will be generated:

prog.nim nim
    
    
    # Dynamically generate "include url_<projectname>.nim" via -d: argument on 
command-line during compile-time
    #  See: script lx
    #       
https://nim-lang.org/docs/manual.html#implementation-specific-pragmas-compileminustime-define-pragmas
    #       
https://stackoverflow.com/questions/67170501/how-can-i-include-a-file-via-a-variables-value
    #
    macro generateInclude(arg: static[string]): untyped =
      newTree(nnkIncludeStmt, newLit(arg))
    const include_urlc {.strdefine.}: string = "url_SKELETON.nim" # default if 
no project name defined
    const include_urlc_path = include_urlc
    generateInclude(include_urlc_path)
    
    
    Run

Compile script lx.awk (extract):

awk
    
    
      if(length(ARGV[1]) > 0) {
        if(checkexists("url_" ARGV[1] ".nim") > 0)
          out = "-d:include_urlc=url_" ARGV[1] ".nim --out:prog-" ARGV[1]
        else
          out = "--out:prog-" ARGV[1]
      }
    
    
    Run

The script is run like `./lx projname` with "projname" given on ARGV[1] which 
will `--out:` a binary named `prog-projname` .. it checks for existence of 
filename `url_projname.nim` and if found adds a compile option 
`-d:include_urlc=url_projname.nim` which is then picked up by prog.nim via a 
compile-time define pragma to create a statement via the `macro 
generateInclude` to `include` that file.

Thus it is possible to dynamically `include` during compile.

Reply via email to