CodegenDecl pragma

The codegenDecl pragma can be used to directly influence Nim’s code generator. It receives a format string that determines how the variable, proc or object type is declared in the generated code.

For variables, $1 in the format string represents the type of the variable, $2 is the name of the variable, and each appearance of $# represents $1/$2 respectively according to its position.

The following Nim code:

  1. var
  2. a {.codegenDecl: "$# progmem $#".}: int

will generate this C code:

  1. int progmem a

For procedures, $1 is the return type of the procedure, $2 is the name of the procedure, $3 is the parameter list, and each appearance of $# represents $1/$2/$3 respectively according to its position.

The following nim code:

  1. proc myinterrupt() {.codegenDecl: "__interrupt $# $#$#".} =
  2. echo "realistic interrupt handler"

will generate this code:

  1. __interrupt void myinterrupt()

For object types, the $1 represents the name of the object type, $2 is the list of fields and $3 is the base type.

  1. const strTemplate = """
  2. struct $1 {
  3. $2
  4. };
  5. """
  6. type Foo {.codegenDecl:strTemplate.} = object
  7. a, b: int

will generate this code:

  1. struct Foo {
  2. NI a;
  3. NI b;
  4. };