3-Tutorial Part 1 - "Hello World" - Libgccjit 13.2.0 Documentation
3-Tutorial Part 1 - "Hello World" - Libgccjit 13.2.0 Documentation
Before we look at the details of the API, let’s look at building and running programs that use the Tutorial
library.
Next topic
Here’s a toy “hello world” program that uses the library to synthesize a call to printf and uses it
to write a message to stdout. Tutorial part 2: Creating a
trivial machine code function
Don’t worry about the content of the program for now; we’ll cover the details in later parts of
this tutorial. This Page
Show Source
/* Smoketest example for libgccjit.so
Copyright (C) 2014-2023 Free Software Foundation, Inc.
Quick search
This file is part of GCC.
Go
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include <libgccjit.h>
#include <stdlib.h>
#include <stdio.h>
static void
create_code (gcc_jit_context *ctxt)
{
/* Let's try to inject the equivalent of:
void
greet (const char *name)
{
printf ("hello %s\n", name);
}
*/
gcc_jit_type *void_type =
gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID);
gcc_jit_type *const_char_ptr_type =
gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CONST_CHAR_PTR);
gcc_jit_param *param_name =
gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "name");
gcc_jit_function *func =
gcc_jit_context_new_function (ctxt, NULL,
GCC_JIT_FUNCTION_EXPORTED,
void_type,
"greet",
1, ¶m_name,
0);
gcc_jit_param *param_format =
gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "format");
gcc_jit_function *printf_func =
gcc_jit_context_new_function (ctxt, NULL,
GCC_JIT_FUNCTION_IMPORTED,
gcc_jit_context_get_type (
ctxt, GCC_JIT_TYPE_INT),
"printf",
1, ¶m_format,
1);
gcc_jit_rvalue *args[2];
args[0] = gcc_jit_context_new_string_literal (ctxt, "hello %s\n");
args[1] = gcc_jit_param_as_rvalue (param_name);
gcc_jit_block_add_eval (
block, NULL,
gcc_jit_context_new_call (ctxt,
NULL,
printf_func,
2, args));
gcc_jit_block_end_with_void_return (block, NULL);
}
int
main (int argc, char **argv)
{
gcc_jit_context *ctxt;
gcc_jit_result *result;
gcc_jit_context_release (ctxt);
gcc_jit_result_release (result);
return 0;
}
Assuming you have the jit library installed, build the test program using:
$ gcc \
tut01-hello-world.c \
-o tut01-hello-world \
-lgccjit
$ ./tut01-hello-world
hello world
libgccjit 13.2.0 ( ) documentation » Tutorial » Tutorial part 1: “Hello world” previous | next | index
© Copyright 2014-2023 Free Software Foundation, Inc.. Created using Sphinx 5.3.0.