Your First Program With UNIT

This section provides instructions on how to build a “hello world” program with UNIT.

Example

Start with some C code using UNIT:

main.c
 1#include <unit/unit.h>
 2
 3int main(void)
 4{
 5    UNIT_Context context;
 6    UNIT_Context_Init(&context);
 7    UNIT_Procedure procedure;
 8    UNIT_Procedure_Init(&procedure, &context, "main");
 9
10    // Pushes the string "Hello, world!" onto the virtual stack
11    UNIT_Procedure_AddStringLoad(&procedure, "Hello, world!");
12
13    // Calls "puts" and consume 1 argument off the virtual stack.
14    // (In this case, that means our string "Hello, world!" will be consumed.)
15    UNIT_Procedure_AddCall(&procedure, "puts", 1);
16
17    // The top of the stack is now the result of calling puts().
18    // We don't actually care about it, so we pop it off.
19    UNIT_Procedure_AddOperation(&procedure, UNIT_OP_POP, 0 /* This value doesn't matter for POP */);
20
21    // Now, we want to return 0.
22    // First, push 0 onto the stack, which will be consumed by the UNIT_OP_RETURN_VALUE opcode.
23    UNIT_Procedure_AddOperation(&procedure, UNIT_OP_LOAD_INTEGER, 0);
24    UNIT_Procedure_AddOperation(&procedure, UNIT_OP_RETURN_VALUE, 0 /* doesn't matter */);
25
26    // Finally, we can compile our procedure into an object file
27    UNIT_CompiledProcedure *compiled = UNIT_Compile(&procedure, UNIT_ARCH_AMD64);
28    UNIT_CompiledProcedure_WriteObjectFile(compiled, "test.o", UNIT_FORMAT_ELF);
29    UNIT_CompiledProcedure_Free(compiled);
30
31    // Clean up the procedure and context
32    UNIT_Procedure_Clear(&procedure);
33    UNIT_Context_Clear(&context);
34    return 0;
35}

Note

The above code does not have proper error handling. In real applications, each call needs to be inside of a UNIT_FAILED check.

Compiling and running the example