From 299e711a77f1c4e47c35f26735d7b5a3d1ec0571 Mon Sep 17 00:00:00 2001 From: Grzegorz Adam Hankiewicz Date: Sun, 22 Jun 2014 17:22:23 +0200 Subject: [PATCH] Adds nimrod to backend examples. --- doc/backends.txt | 70 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/doc/backends.txt b/doc/backends.txt index 9d57450dd0..957a2d2ed4 100644 --- a/doc/backends.txt +++ b/doc/backends.txt @@ -141,9 +141,75 @@ To wrap native code, take a look at the `c2nim tool `_ which helps with the process of scanning and transforming header files into a Nimrod interface. -Example in C. +C invocation example +~~~~~~~~~~~~~~~~~~~~ -Example in JS. +Create a ``logic.c`` file with the following content: + +.. code-block:: c + int addTwoIntegers(int a, int b) + { + return a + b; + } + +Create a ``calculator.nim`` file with the following content: + +.. code-block:: nimrod + + {.compile: "logic.c".} + proc addTwoIntegers(a, b: int): int {.importc.} + + when isMainModule: + echo addTwoIntegers(3, 7) + +With these two files in place, you can run ``nimrod c -r calculator.nim`` and +the Nimrod compiler will compile the ``logic.c`` file in addition to +``calculator.nim`` and link both into an executable, which outputs ``10`` when +run. Another way to link the C file statically and get the same effect would +be remove the line with the ``compile`` pragma and run the following typical +Unix commands:: + + $ gcc -c logic.c + $ ar rvs mylib.a logic.o + $ nimrod c --passL:mylib.a -r calculator.nim + +Just like in this example we pass the path to the ``mylib.a`` library (and we +could as well pass ``logic.o``) we could be passing switches to link any other +static C library. + + +JavaScript invocation example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Create a ``host.html`` file with the following content: + +.. code-block:: + + + + + + +Create a ``calculator.nim`` file with the following content (or reuse the one +from the previous section): + +.. code-block:: nimrod + + proc addTwoIntegers(a, b: int): int {.importc.} + + when isMainModule: + echo addTwoIntegers(3, 7) + +Compile the Nimrod code to JavaScript with ``nimrod js -o:calculator.js +calculator.nim`` and open ``host.html`` in a browser. If the browser supports +javascript, you should see the value ``10``. In JavaScript the `echo proc +`_ will modify the HTML DOM and append the string. Use the +`dom module `_ for specific DOM querying and modification procs. Backend code calling Nimrod