Consider this C function:
int loop_test (int n) { int sum = 0; for (int i = 0; i < n; i++) sum += i * i; return sum; }
This example demonstrates some more features of libgccjit, with local variables and a loop.
To break this down into libgccjit terms, it’s usually easier to reword the for loop as a while loop, giving:
int loop_test (int n) { int sum = 0; int i = 0; while (i < n) { sum += i * i; i++; } return sum; }
Here’s what the final control flow graph will look like:
![]()
Figure
As before, we include the libgccjit++ header and make a gccjit;;context.
#include <libgccjit++.h> void test (void) { gccjit::context ctxt; ctxt = gccjit::context::acquire ();
The function works with the C int type.
In the previous tutorial we acquired this via
gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_INT);
though we could equally well make it work on, say, double:
gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
For integer types we can use gccjit::context::get_int_type
to directly bind a specific type:
gccjit::type the_type = ctxt.get_int_type <int> ();
Let’s build the function:
gcc_jit_param n = ctxt.new_param (the_type, "n"); std::vector<gccjit::param> params; params.push_back (n); gccjit::function func = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED, return_type, "loop_test", params, 0);