Simple Guile Example

Okay, enough philosophizing and preparing. Here is a simple hybrid C/Guile program that prints out the string Hello world. It is a tiny program, but it demonstrates some basic examples of Guile extensions, including how to initialize the Guile interpreter, how to read in a Guile script, and how to call a Guile function from C.

The program has two source files. One file, main.c, contains the C code. The other source file, script.scm contains the Guile code. Lastly, there is a Makefile to control program compilation.

Example 1. The "hello world" example: main.c

#include <stdio.h>
#include <stdlib.h>
#include <libguile.h>

int main (int argc, char *argv[])
	SCM func_symbol;
	SCM func;
	// Load the scheme function definitions
	scm_c_primitive_load ("script.scm");	
	func_symbol = scm_c_lookup("do-hello");
	func = scm_variable_ref(func_symbol);
	scm_call_0 (func);



Example 2. The "hello world" example: script.scm.

(define do-hello
  (lambda ()
    (display "Hello world.") 


This is the Makefile to control compilation. Note that is uses a shell escape to call the guile-config command.

CDEBUG = -g -Wall
CFLAGS = $(CDEBUG) `guile-config compile`
LDFLAGS = `guile-config link`

SRCS = main.c
OBJS = main.o

hello_world: $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)


Using a text editor, edit the three files and save them in the same directory. Then run make to compile the program. If all has gone according to plan, an executable named hello_world should have been created.

Running hello_world will generate the following output: Hello world.