# Compiling a context

Once populated, a `gccjit.Context` can be compiled to machine code, either in-memory via `gccjit.Context.compile()` or to disk via `gccjit.Context.compile_to_file()`.

You can compile a context multiple times (using either form of compilation), although any errors that occur on the context will prevent any future compilation of that context.

## In-memory compilation

gccjit.Context.compile(self)

  > rtype:

  >   `gccjit.Result`

  This calls into GCC and builds the code, returning a `gccjit.Result`.

class gccjit.Result

  A `gccjit.Result` encapsulates the result of compiling a `gccjit.Context` in-memory, and the lifetimes of any machine code functions or globals that are within the result.

  get_code(funcname)

    Locate the given function within the built machine code.

    Functions are looked up by name. For this to succeed, a function with a name matching funcname must have been created on result’s context (or a parent context) via a call to `gccjit.Context.new_function()` with kind `gccjit.FunctionKind.EXPORTED`.

    The returned value is an int, actually a pointer to the machine code within the address space of the process. This will need to be wrapped up with ctypes to be callable:

        import ctypes

        # "[int] -> int" functype:
        int_int_func_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
        code = int_int_func_type(jit_result.get_code(b"square"))
        assert code(5) == 25

    The code has the same lifetime as the `gccjit.Result` instance; the pointer becomes invalid when the result instance is cleaned up.

## Ahead-of-time compilation

Although libgccjit is primarily aimed at just-in-time compilation, it can also be used for implementing more traditional ahead-of-time compilers, via the `gccjit.Context.compile_to_file()` API entrypoint.

gccjit.Context.compile_to_file(self, kind, path)

  Compile the context to a file of the given kind:

      ctxt.compile_to_file(gccjit.OutputKind.EXECUTABLE,
                           'a.out')

  `gccjit.Context.compile_to_file()` ignores the suffix of `path`, and insteads uses kind to decide what to do.

  Note

  This is different from the `gcc` program, which does make use of the suffix of the output file when determining what to do.

  The available kinds of output are:

  Output kind | Typical suffix
  --- | ---
  `gccjit.OutputKind.ASSEMBLER` | .s
  `gccjit.OutputKind.OBJECT_FILE` | .o
  `gccjit.OutputKind.DYNAMIC_LIBRARY` | .so or .dll
  `gccjit.OutputKind.EXECUTABLE` | None, or .exe

class gccjit.OutputKind
  ASSEMBLER

    Compile the context to an assembler file.

  OBJECT_FILE

    Compile the context to an object file.

  DYNAMIC_LIBRARY

    Compile the context to a dynamic library.

    There is currently no support for specifying other libraries to link against.

  EXECUTABLE

    Compile the context to an executable.

    There is currently no support for specifying libraries to link against.