code:
\input texinfo
@c -*-texinfo-*-
@c %**start of header
@setfilename guile.info
@settitle Guile Reference Manual
@set guile
@set MANUAL-REVISION 1
@c %**end of header
@include version.texi
@include lib-version.texi
@include effective-version.texi

@copying
This manual documents Guile version @value{VERSION}.

Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2009, 2010 Free
Software Foundation.

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with
no Invariant Sections, with the Front-Cover Texts being ``A GNU
Manual,'' and with the Back-Cover Text ``You are free to copy and
modify this GNU Manual.''.  A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
@end copying

@c Notes
@c
@c We no longer use the category "primitive" to distinguish C-defined
@c Scheme procedures from those defined in Scheme.  Instead, the
@c reference manual now includes a C declaration as well as a Scheme
@c declaration for each procedure that is available in both Scheme and
@c C.
@c
@c When adding a new reference entry to the Guile manual, please
@c document it with @deffn using one of the following categories:
@c
@c   {Scheme Procedure}
@c   {Scheme Syntax}
@c   {C Function}
@c   {C Macro}
@c
@c If the entry is for a new primitive, it should have both a @deffn
@c {Scheme Procedure} line and a @deffnx {C Function} line; see the
@c manual source for plenty of existing examples of this.
@c
@c For {C Function} entries where the return type and all parameter
@c types are SCM, we omit the SCMs.  This is easier to read and also
@c gets round the problem that Texinfo doesn't allow a @deftypefnx
@c inside a @deffn.
@c
@c For a list of Guile primitives that are not yet incorporated into the
@c reference manual, see the file `new-docstrings.texi', which holds all
@c the docstrings snarfed from the libguile C sources for primitives
@c that are not in the reference manual.  If you have worked with some
@c of these concepts, implemented them, or just happen to know what they
@c do, please write up a little explanation -- it would be a big help.
@c Alternatively, if you know of any reason why some of these should
@c *not* go in the manual, please let the mailing list
@c <guile-devel@gnu.org> know.

@c Define indices that are used in the Guile Scheme part of the
@c reference manual to group stuff according to whether it is R5RS or a
@c Guile extension.
@defcodeindex rn

@c vnew - For (some) new items, indicates the Guile version in which
@c item first appeared.  In future, this could be made to expand to
@c something like a "New in Guile 45!" banner.
@macro vnew{VERSION}
@end macro

@c  The following, @le{} and @ge{}, are standard tex directives, given
@c  definitions for use in non-tex.
@c
@ifnottex
@macro ge
>=
@end macro
@macro le
<=
@end macro
@end ifnottex

@c  @cross{} is a \times symbol in tex, or an "x" in info.  In tex it works
@c  inside or outside $ $.
@tex
\gdef\cross{\ifmmode\times\else$\times$\fi}
@end tex
@ifnottex
@macro cross
x
@end macro
@end ifnottex

@c  @m{T,N} is $T$ in tex or @math{N} otherwise.  This is an easy way to give
@c  different forms for math in tex and info.
@iftex
@macro m {T,N}
@tex$\T\$@end tex
@end macro
@end iftex
@ifnottex
@macro m {T,N}
@math{\N\}
@end macro
@end ifnottex

@c  @nicode{S} is plain S in info, or @code{S} elsewhere.  This can be used
@c  when the quotes that @code{} gives in info aren't wanted, but the
@c  fontification in tex or html is wanted.  @alias is used rather
@c  than @macro because backslashes don't work properly in an @macro.
@ifinfo
@alias nicode=asis
@end ifinfo
@ifnotinfo
@alias nicode=code
@end ifnotinfo

@c @iftex
@c @cropmarks
@c @end iftex

@dircategory The Algorithmic Language Scheme
@direntry
* Guile Reference: (guile).     The Guile reference manual.
@end direntry

@setchapternewpage odd

@titlepage
@sp 10
@comment The title is printed in a large font.
@title Guile Reference Manual
@subtitle Edition @value{EDITION}, revision @value{MANUAL-REVISION}, for use with Guile @value{VERSION}
@c @subtitle $Id: guile.texi,v 1.49 2008-03-19 22:51:23 ossau Exp $

@c See preface.texi for the list of authors
@author The Guile Developers

@c The following two commands start the copyright page.
@page
@vskip 0pt plus 1filll
@vskip 0pt plus 1filll
@insertcopying
@end titlepage

@c @smallbook
@finalout
@headings double

@c Where to find Guile examples.
@set example-dir doc/examples

@ifnottex
@node Top, Preface, (dir), (dir)
@top The Guile Reference Manual

@insertcopying
@sp 1
@end ifnottex

@menu

* Preface::
* Introduction::

* Hello Guile!::
* Hello Scheme!::

* Programming in Scheme::
* Programming in C::

* API Reference::

* Guile Modules::
* Standard Library::

* GOOPS::

* Guile Implementation::

* Autoconf Support::

Appendices

* GNU Free Documentation License::  The license of this manual.

Indices

* Concept Index::
* Procedure Index::
* Variable Index::
* Type Index::
* R5RS Index::

@end menu

@contents

@include preface.texi

@include intro.texi

@include tour.texi

@include scheme-ideas.texi
@include scheme-reading.texi

@node Programming in Scheme
@chapter Programming in Scheme

Guile's core language is Scheme, and a lot can be achieved simply by using Guile
to write and run Scheme programs --- as opposed to having to dive into C code.
In this part of the manual, we explain how to use Guile in this mode, and
describe the tools that Guile provides to help you with script writing,
debugging and packaging your programs for distribution.

For detailed reference information on the variables, functions
etc. that make up Guile's application programming interface (API),
@xref{API Reference}.

@menu
* Guile Scheme::                Guile's implementation of Scheme.
* Guile Scripting::             How to write Guile scripts.
* Using Guile Interactively::   Guile's REPL features.
* Using Guile in Emacs::        Guile and Emacs.
@end menu

@include scheme-intro.texi
@include scheme-scripts.texi
@include scheme-using.texi

@node Programming in C
@chapter Programming in C

This part of the manual explains the general concepts that you need to
understand when interfacing to Guile from C.  You will learn about how
the latent typing of Scheme is embedded into the static typing of C, how
the garbage collection of Guile is made available to C code, and how
continuations influence the control flow in a C program.

This knowledge should make it straightforward to add new functions to
Guile that can be called from Scheme.  Adding new data types is also
possible and is done by defining @dfn{smobs}.

The @ref{Programming Overview} section of this part contains general
musings and guidelines about programming with Guile.  It explores
different ways to design a program around Guile, or how to embed Guile
into existing programs.

For a pedagogical yet detailed explanation of how the data representation of
Guile is implemented, @xref{Data Representation}. You don't need to know the
details given there to use Guile from C, but they are useful when you want to
modify Guile itself or when you are just curious about how it is all done.

For detailed reference information on the variables, functions
etc. that make up Guile's application programming interface (API),
@xref{API Reference}.

@menu
* Linking Programs With Guile:: More precisely, with the libguile library.
* Linking Guile with Libraries::  To extend Guile itself.
* General Libguile Concepts::   General concepts for using libguile.
* Defining New Types (Smobs)::  Adding new types to Guile.
* Function Snarfing::           A way to define new functions.
* Programming Overview::        An overview of Guile programming.
@end menu

@include libguile-linking.texi
@include libguile-extensions.texi
@include libguile-concepts.texi
@include libguile-smobs.texi
@include libguile-snarf.texi
@include libguile-program.texi

@node API Reference
@chapter API Reference

Guile provides an application programming interface (@dfn{API}) to
developers in two core languages: Scheme and C.  This part of the manual
contains reference documentation for all of the functionality that is
available through both Scheme and C interfaces.

@menu
* API Overview::                Overview of the Guile API.
* Deprecation::                 Obsolete back-compatible APIs.
* The SCM Type::                The fundamental data type for C code.
* Initialization::              Initializing Guile.
* Snarfing Macros::             Macros for snarfing initialization actions.
* Simple Data Types::           Numbers, strings, booleans and so on.
* Compound Data Types::         Data types for holding other data.
* Smobs::                       Defining new data types in C.
* Procedures::                  Procedures.
* Macros::                      Extending the syntax of Scheme.
* Utility Functions::           General utility functions.
* Binding Constructs::          Definitions and variable bindings.
* Control Mechanisms::          Controlling the flow of program execution.
* Input and Output::            Ports, reading and writing.
* LALR(1) Parsing::             Generating LALR(1) parsers.
* Read/Load/Eval/Compile::      Reading and evaluating Scheme code.
* Memory Management::           Memory management and garbage collection.
* Objects::                     Low level object orientation support.
* Modules::                     Designing reusable code libraries.
* Foreign Function Interface::  Interacting with C procedures and data.
* Scheduling::                  Threads, mutexes, asyncs and dynamic roots.
* Options and Config::          Configuration, features and runtime options.
* Other Languages::             Emacs Lisp, ECMAScript, and more.
* Internationalization::        Support for gettext, etc.
* Debugging::                   Debugging infrastructure and Scheme interface.
* Code Coverage::               Gathering code coverage data.
@end menu

@include api-overview.texi
@include api-deprecated.texi
@include api-scm.texi
@include api-init.texi
@include api-snarf.texi
@include api-data.texi
@include api-compound.texi
@include api-smobs.texi
@include api-procedures.texi
@include api-macros.texi
@include api-utility.texi
@include api-binding.texi
@include api-control.texi
@include api-io.texi
@include api-lalr.texi
@include api-evaluation.texi
@include api-memory.texi
@include api-modules.texi
@include api-foreign.texi
@include api-scheduling.texi
@c object orientation support here
@include api-options.texi
@include api-languages.texi
@include api-i18n.texi
@include api-debug.texi
@include api-coverage.texi

@node Guile Modules
@chapter Guile Modules

@menu
* SLIB::                        Using the SLIB Scheme library.
* POSIX::                       POSIX system calls and networking.
* getopt-long::                 Command line handling.
* SRFI Support::                Support for various SRFIs.
* R6RS Support::                Modules defined by the R6RS.
* Readline Support::            Module for using the readline library.
* Pretty Printing::             Nicely formatting Scheme objects for output.
* Formatted Output::            The @code{format} procedure.
* File Tree Walk::              Traversing the file system.
* Queues::                      First-in first-out queuing.
* Streams::                     Sequences of values.
* Buffered Input::              Ports made from a reader function.
* Expect::			Controlling interactive programs with Guile.
* sxml-match::                  Pattern matching of SXML.
* The Scheme shell (scsh)::     Using scsh interfaces in Guile.
* Tracing::                     Tracing program execution.
@end menu

@include slib.texi
@include posix.texi
@include mod-getopt-long.texi
@include srfi-modules.texi
@include r6rs.texi
@include repl-modules.texi
@include misc-modules.texi
@include expect.texi

@c XXX: Would be nicer if it were close to the (sxml simple) documentation.
@include sxml-match.texi

@include scsh.texi
@include scheme-debugging.texi

@node Standard Library
@chapter Standard Library

@lowersections
@include standard-library.texi
@raisesections

@include goops.texi

@node Guile Implementation
@chapter Guile Implementation

At some point, after one has been programming in Scheme for some time,
another level of Scheme comes into view: its implementation. Knowledge
of how Scheme can be implemented turns out to be necessary to become
an expert hacker. As Peter Norvig notes in his retrospective on
PAIP@footnote{PAIP is the common abbreviation for @cite{Paradigms of
Artificial Intelligence Programming}, an old but still useful text on
Lisp. Norvig's retrospective sums up the lessons of PAIP, and can be
found at @uref{http://norvig.com/Lisp-retro.html}.}, ``The expert Lisp
programmer eventually develops a good `efficiency model'.''

By this Norvig means that over time, the Lisp hacker eventually
develops an understanding of how much her code ``costs'' in terms of
space and time.

This chapter describes Guile as an implementation of Scheme: its
history, how it represents and evaluates its data, and its compiler.
This knowledge can help you to make that step from being one who is
merely familiar with Scheme to being a real hacker.

@menu
* History::                          A brief history of Guile.
* Data Representation::              How Guile represents Scheme data.
* A Virtual Machine for Guile::      How compiled procedures work.
* Compiling to the Virtual Machine:: Not as hard as you might think.
@end menu

@include history.texi
@include data-rep.texi
@include vm.texi
@include compiler.texi

@include autoconf.texi

@node GNU Free Documentation License
@appendix GNU Free Documentation License

@include fdl.texi

@iftex
@page
@unnumbered{Indices}
@end iftex

@include indices.texi
@include scheme-indices.texi

@bye

license: mit


code:
%!PS-Adobe-2.0 EPSF
%%Title: /tmp/xfig-fig016295
%%Creator: fig2dev
%%CreationDate: Fri Jun 10 23:18:16 1994
%%For: eg@kaolin (Erick Gallesio)
%%BoundingBox: 0 0 361 217
%%Pages: 0
%%EndComments
/$F2psDict 200 dict def
$F2psDict begin
$F2psDict /mtrx matrix put
/l {lineto} bind def
/m {moveto} bind def
/s {stroke} bind def
/n {newpath} bind def
/gs {gsave} bind def
/gr {grestore} bind def
/clp {closepath} bind def
/graycol {dup dup currentrgbcolor 4 -2 roll mul 4 -2 roll mul
4 -2 roll mul setrgbcolor} bind def
/col-1 {} def
/col0 {0 0 0 setrgbcolor} bind def
/col1 {0 0 1 setrgbcolor} bind def
/col2 {0 1 0 setrgbcolor} bind def
/col3 {0 1 1 setrgbcolor} bind def
/col4 {1 0 0 setrgbcolor} bind def
/col5 {1 0 1 setrgbcolor} bind def
/col6 {1 1 0 setrgbcolor} bind def
/col7 {1 1 1 setrgbcolor} bind def
	end
/$F2psBegin {$F2psDict begin /$F2psEnteredState save def} def
/$F2psEnd {$F2psEnteredState restore end} def
%%EndProlog

$F2psBegin
0 setlinecap 0 setlinejoin
-216.0 288.0 translate 0.900 -0.900 scale
0.500 setlinewidth
n 309 159 m 309 159 l gs col-1 s gr
n 246.401 216.889 m 244.000 209.000 l 249.831 214.831 l gs 2 setlinejoin col-1 s gr
% Polyline
n 244 209 m 274 259 l gs col-1 s gr
n 298.169 214.831 m 304.000 209.000 l 301.599 216.889 l gs 2 setlinejoin col-1 s gr
% Polyline
n 304 209 m 274 259 l gs col-1 s gr
n 255.721 213.778 m 249.000 209.000 l 257.179 210.053 l gs 2 setlinejoin col-1 s gr
% Polyline
n 249 209 m 364 254 l gs col-1 s gr
n 370.312 216.376 m 374.000 209.000 l 374.217 217.243 l gs 2 setlinejoin col-1 s gr
% Polyline
n 374 209 m 364 254 l gs col-1 s gr
n 283.772 280.725 m 279.000 274.000 l 286.376 277.688 l gs 2 setlinejoin col-1 s gr
% Polyline
n 279 274 m 314 304 l gs col-1 s gr
n 351.457 272.333 m 359.000 269.000 l 353.913 275.490 l gs 2 setlinejoin col-1 s gr
% Polyline
n 359 269 m 314 304 l gs col-1 s gr
n 300.950 165.789 m 309.000 164.000 l 302.739 169.367 l gs 2 setlinejoin col-1 s gr
% Polyline
n 309 164 m 249 194 l gs col-1 s gr
n 307.000 172.000 m 309.000 164.000 l 311.000 172.000 l gs 2 setlinejoin col-1 s gr
% Polyline
n 309 164 m 309 199 l gs col-1 s gr
n 315.261 169.367 m 309.000 164.000 l 317.050 165.789 l gs 2 setlinejoin col-1 s gr
% Polyline
n 309 164 m 379 199 l gs col-1 s gr
n 406.949 101.701 m 404.000 94.000 l 410.226 99.407 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 439 144 l gs col-1 s gr
n 410.363 99.245 m 404.000 94.000 l 412.083 95.634 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 509 144 l gs col-1 s gr
n 411.173 98.068 m 404.000 94.000 l 412.243 94.214 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 584 144 l gs col-1 s gr
n 396.075 96.277 m 404.000 94.000 l 398.079 99.739 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 309 149 l gs col-1 s gr
% Polyline
n 584 229 m 584 204 l gs col-1 s gr
n 582.000 212.000 m 584.000 204.000 l 586.000 212.000 l gs 2 setlinejoin col-1 s gr
% Polyline
n 584 189 m 584 159 l gs col-1 s gr
n 582.000 167.000 m 584.000 159.000 l 586.000 167.000 l gs 2 setlinejoin col-1 s gr
/Times-Bold findfont 12.00 scalefont setfont
239 209 m
gs 1 -1 scale (A) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
274 274 m
gs 1 -1 scale (D) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
359 269 m
gs 1 -1 scale (E) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
304 209 m
gs 1 -1 scale (B) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
374 209 m
gs 1 -1 scale (C) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
314 319 m
gs 1 -1 scale (F) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
289 159 m
gs 1 -1 scale (<object>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
389 89 m
gs 1 -1 scale (<top>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
424 154 m
gs 1 -1 scale (<pair>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
474 154 m
gs 1 -1 scale (<procedure>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
559 154 m
gs 1 -1 scale (<number>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
629 154 m
gs 1 -1 scale (...) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
569 199 m
gs 1 -1 scale (<real>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
559 239 m
gs 1 -1 scale (<integer>) col-1 show gr
$F2psEnd


code:
%PDF-1.3
%�쏢
5 0 obj
<</Length 6 0 R/Filter /FlateDecode>>
stream
x�m��n1E��
-�Ű�(��6-�][�.�
�y�)���Ҽ���w�(��u���g�_o͇���1���3l_M�l9�b����i�}0�(:U[|�[�-�:s��"V!�zir� ��E��/N�-�#K5�n[���{��r�E#��]�%�w
��af�J�A�<�#�"���n	��J=u���F�$9��"T�ZQAn*P�m��H�XɎ�+s��d"�st�	1���sU�.a�-<�pS�9Chፒc��L�e�8�tӮ*4"w!çJi�M��ff�i�	���s���z��^]��1&�d��=��E8{�^x��ㄖK=M�!T����͊k�A��${�4�'!k޻!��W��)M�%��D�1��Ă�G���\��6�d�+񀉔PL5�2�����<��d�Ī��ld.�^n���%�L�Naq5O�ݜ��$�*���7ɞ�a���ܙW�t�]��zk/V�b��dW�M?��v�R
~V[���\aƘ��oW�f���
��Z����S-W��e�#�,>-���b;�{UijdS[gU�����f�v^=��(������8��������|ٱG�Ą��y�����T��������ͦ��P���ZA�>���cۨC���x�������~�2����(8endstream
endobj
6 0 obj
660
endobj
4 0 obj
<</Type/Page/MediaBox [0 0 361 217]
/Parent 3 0 R
/Resources<</ProcSet[/PDF /Text]
/ExtGState 9 0 R
/Font 10 0 R
>>
/Contents 5 0 R
>>
endobj
3 0 obj
<< /Type /Pages /Kids [
4 0 R
] /Count 1
>>
endobj
1 0 obj
<</Type /Catalog /Pages 3 0 R
>>
endobj
7 0 obj
<</Type/ExtGState
/OPM 1>>endobj
9 0 obj
<</R7
7 0 R>>
endobj
10 0 obj
<</R8
8 0 R>>
endobj
8 0 obj
<</BaseFont/Times-Bold/Type/Font
/Subtype/Type1>>
endobj
2 0 obj
<</Producer(GPL Ghostscript 8.15)
/CreationDate(D:20060418115825)
/ModDate(D:20060418115825)
/Title(/tmp/xfig-fig016295)
/Creator(fig2dev)
/Author(eg@kaolin \(Erick Gallesio\))>>endobj
xref
0 11
0000000000 65535 f
0000000973 00000 n
0000001186 00000 n
0000000914 00000 n
0000000764 00000 n
0000000015 00000 n
0000000745 00000 n
0000001021 00000 n
0000001121 00000 n
0000001062 00000 n
0000001091 00000 n
trailer
<< /Size 11 /Root 1 0 R /Info 2 0 R
/ID [(��Cce��3f�q\\[)(��Cce��3f�q\\[)]
>>
startxref
1379
%%EOF


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  2008, 2010
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node History
@section A Brief History of Guile

Guile is an artifact of historical processes, both as code and as a
community of hackers. It is sometimes useful to know this history when
hacking the source code, to know about past decisions and future
directions.

Of course, the real history of Guile is written by the hackers hacking
and not the writers writing, so we round up the section with a note on
current status and future directions.

@menu
* The Emacs Thesis::
* Early Days::
* A Scheme of Many Maintainers::
* A Timeline of Selected Guile Releases::
* Status::
@end menu

@node The Emacs Thesis
@subsection The Emacs Thesis

The story of Guile is the story of bringing the development experience
of Emacs to the mass of programs on a GNU system.

Emacs, when it was first created in its GNU form in 1984, was a new
take on the problem of ``how to make a program''. The Emacs thesis is
that it is delightful to create composite programs based on an
orthogonal kernel written in a low-level language together with a
powerful, high-level extension language.

Extension languages foster extensible programs, programs which adapt
readily to different users and to changing times. Proof of this can be
seen in Emacs' current and continued existence, spanning more than a
quarter-century.

Besides providing for modification of a program by others, extension
languages are good for @emph{intension} as well. Programs built in
``the Emacs way'' are pleasurable and easy for their authors to flesh
out with the features that they need.

After the Emacs experience was appreciated more widely, a number of
hackers started to consider how to spread this experience to the rest
of the GNU system. It was clear that the easiest way to Emacsify a
program would be to embed a shared language implementation into it.

@node Early Days
@subsection Early Days

Tom Lord was the first to fully concentrate his efforts on an
embeddable language runtime, which he named ``GEL'', the GNU Extension
Language.

GEL was the product of converting SCM, Aubrey Jaffer's implementation
of Scheme, into something more appropriate to embedding as a library.
(SCM was itself based on an implementation by George Carrette, SIOD.)

Lord managed to convince Richard Stallman to dub GEL the official
extension language for the GNU project. It was a natural fit, given
that Scheme was a cleaner, more modern Lisp than Emacs Lisp. Part of
the argument was that eventually when GEL became more capable, it
could gain the ability to execute other languages, especially Emacs
Lisp.

Due to a naming conflict with another programming language, Jim Blandy
suggested a new name for GEL: ``Guile''. Besides being a recursive
acronym, ``Guile'' craftily follows the naming of its ancestors,
``Planner'', ``Conniver'', and ``Schemer''. (The latter was truncated
to ``Scheme'' due to a 6-character file name limit on an old operating
system.) Finally, ``Guile'' suggests ``guy-ell'', or ``Guy L.
Steele'', who, together with Gerald Sussman, originally discovered
Scheme.

Around the same time that Guile (then GEL) was readying itself for
public release, another extension language was gaining in popularity,
Tcl. Many developers found advantages in Tcl because of its shell-like
syntax and its well-developed graphical widgets library, Tk. Also, at
the time there was a large marketing push promoting Tcl as a
``universal extension language''.

Richard Stallman, as the primary author of GNU Emacs, had a particular
vision of what extension languages should be, and Tcl did not seem to
him to be as capable as Emacs Lisp. He posted a criticism to the
comp.lang.tcl newsgroup, sparking one of the internet's legendary
flamewars. As part of these discussions, retrospectively dubbed the
``Tcl Wars'', he announced the Free Software Foundation's intent to
promote Guile as the extension language for the GNU project.

It is a common misconception that Guile was created as a reaction to
Tcl. While it is true that the public announcement of Guile happened
at the same time as the ``Tcl wars'', Guile was created out of a
condition that existed outside the polemic. Indeed, the need for a
powerful language to bridge the gap between extension of existing
applications and a more fully dynamic programming environment is still
with us today.

@node A Scheme of Many Maintainers
@subsection A Scheme of Many Maintainers

Surveying the field, it seems that Scheme implementations correspond
with their maintainers on an N-to-1 relationship. That is to say, that
those people that implement Schemes might do so on a number of
occasions, but that the lifetime of a given Scheme is tied to the
maintainership of one individual.

Guile is atypical in this regard.

Tom Lord maintained Guile for its first year and a half or so,
corresponding to the end of 1994 through the middle of 1996. The
releases made in this time constitute an arc from SCM as a standalone
program to Guile as a reusable, embeddable library, but passing
through a explosion of features: embedded Tcl and Tk, a toolchain for
compiling and disassembling Java, addition of a C-like syntax,
creation of a module system, and a start at a rich POSIX interface.

Only some of those features remain in Guile. There were ongoing
tensions between providing a small, embeddable language, and one which
had all of the features (e.g. a graphical toolkit) that a modern Emacs
might need. In the end, as Guile gained in uptake, the development
team decided to focus on depth, documentation and orthogonality rather
than on breadth. This has been the focus of Guile ever since, although
there is a wide range of third-party libraries for Guile.

Jim Blandy presided over that period of stabilization, in the three
years until the end of 1999, when he too moved on to other projects.
Since then, Guile has had a group maintainership. The first group was
Maciej Stachowiak, Mikael Djurfeldt, and Marius Vollmer, with Vollmer
staying on the longest. By late 2007, Vollmer had mostly moved on to
other things, so Neil Jerram and Ludovic Courtès stepped up to take on
the primary maintenance responsibility. Jerram and Courtès were joined
by Andy Wingo in late 2009.

Of course, a large part of the actual work on Guile has come from
other contributors too numerous to mention, but without whom the world
would be a poorer place.

@node A Timeline of Selected Guile Releases
@subsection A Timeline of Selected Guile Releases

@table @asis
@item guile-i --- 4 February 1995
SCM, turned into a library.

@item guile-ii --- 6 April 1995
A low-level module system was added. Tcl/Tk support was added,
allowing extension of Scheme by Tcl or vice versa. POSIX support was
improved, and there was an experimental stab at Java integration.

@item guile-iii --- 18 August 1995
The C-like syntax, ctax, was improved, but mostly this release
featured a start at the task of breaking Guile into pieces.

@item 1.0 --- 5 January 1997
@code{#f} was distinguished from @code{'()}. User-level, cooperative
multi-threading was added. Source-level debugging became more useful,
and programmer's and user's manuals were begun. The module system
gained a high-level interface, which is still used today in more or
less the same form.

@item 1.1 --- 16 May 1997
@itemx 1.2 --- 24 June 1997
Support for Tcl/Tk and ctax were split off as separate packages, and
have remained there since. Guile became more compatible with SCSH, and
more useful as a UNIX scripting language. Libguile could now be built as
a shared library, and third-party extensions written in C became
loadable via dynamic linking.

@item 1.3.0 --- 19 October 1998
Command-line editing became much more pleasant through the use of the
readline library. The initial support for internationalization via
multi-byte strings was removed; 10 years were to pass before proper
internationalization would land again. Initial Emacs Lisp support
landed, ports gained better support for file descriptors, and fluids
were added.

@item 1.3.2 --- 20 August 1999
@itemx 1.3.4 --- 25 September 1999
@itemx 1.4 --- 21 June 2000
A long list of lispy features were added: hooks, Common Lisp's
@code{format}, optional and keyword procedure arguments,
@code{getopt-long}, sorting, random numbers, and many other fixes and
enhancements. Guile also gained an interactive debugger, interactive
help, and better backtraces.

@item 1.6 --- 6 September 2002
Guile gained support for the R5RS standard, and added a number of SRFI
modules. The module system was expanded with programmatic support for
identifier selection and renaming. The GOOPS object system was merged
into Guile core.

@item 1.8 --- 20 February 2006
Guile's arbitrary-precision arithmetic switched to use the GMP
library, and added support for exact rationals. Guile's embedded
user-space threading was removed in favor of POSIX pre-emptive
threads, providing true multiprocessing. Gettext support was added,
and Guile's C API was cleaned up and orthogonalized in a massive way.

@item 2.0 --- April 2010
A virtual machine was added to Guile, along with the associated compiler
and toolchain. Support for internationalization was finally
reimplemented, in terms of unicode, locales, and libunistring. Running
Guile instances became controllable and debuggable from within Emacs,
via GDS and Geiser. Guile caught up to features found in a number of
other Schemes: SRFI-18 threads, including thread cancellation,
module-hygienic macros, a profiler, tracer, and debugger, SSAX XML
integration, bytevectors, module versions, and partial support for R6RS.
@end table

@node Status
@subsection Status, or: Your Help Needed

Guile has achieved much of what it set out to achieve, but there is
much remaining to do.

There is still the old problem of bringing existing applications into
a more Emacs-like experience. Guile has had some successes in this
respect, but still most applications in the GNU system are without
Guile integration.

Getting Guile to those applications takes an investment, the
``hacktivation energy'' needed to wire Guile into a program that only
pays off once it is good enough to enable new kinds of behavior. This
would be a great way for new hackers to contribute: take an
application that you use and that you know well, think of something
that it can't yet do, and figure out a way to integrate Guile and
implement that task in Guile.

With time, perhaps this exposure can reverse itself, whereby programs
can run under Guile instead of vice versa, eventually resulting in the
Emacsification of the entire GNU system. Indeed, this is the reason
for the naming of the many Guile modules that live in the @code{ice-9}
namespace, a nod to the fictional substance in Kurt Vonnegut's
novel, Cat's Cradle, capable of acting as a seed crystal to
crystallize the mass of software.

Implicit to this whole discussion is the idea that dynamic languages
are somehow better than languages like C. While languages like C have
their place, Guile's take on this question is that yes, Scheme is more
expressive than C, and more fun to write. This realization carries an
imperative with it to write as much code in Scheme as possible rather
than in other languages.

These days it is possible to write extensible applications almost
entirely from high-level languages, through byte-code and native
compilation, speed gains in the underlying hardware, and foreign call
interfaces in the high-level language. Smalltalk systems are like
this, as are Common Lisp-based systems. While there already are a
number of pure-Guile applications out there, users still need to drop
down to C for some tasks: interfacing to system libraries that don't
have prebuilt Guile interfaces, and for some tasks requiring high
performance.

The addition of the virtual machine in Guile 2.0, together with the
compiler infrastructure, should go a long way to addressing the speed
issues. But there is much optimization to be done. Interested
contributors will find lots of delightful low-hanging fruit, from
simple profile-driven optimization to hacking a just-in-time compiler
from VM bytecode to native code.

Still, even with an all-Guile application, sometimes you want to
provide an opportunity for users to extend your program from a
language with a syntax that is closer to C, or to Python. Another
interesting idea to consider is compiling e.g. Python to Guile. It's
not that far-fetched of an idea: see for example IronPython or JRuby.

And then there's Emacs itself. Though there is a somewhat-working Emacs
Lisp language frontend for Guile, it cannot yet execute all of Emacs
Lisp. A serious integration of Guile with Emacs would replace the Elisp
virtual machine with Guile, and provide the necessary C shims so that
Guile could emulate Emacs' C API. This would give lots of exciting
things to Emacs: native threads, a real object system, more
sophisticated types, cleaner syntax, and access to all of the Guile
extensions.

Finally, there is another axis of crystallization, the axis between
different Scheme implementations. Guile does not yet support the
latest Scheme standard, R6RS, and should do so. Like all standards,
R6RS is imperfect, but supporting it will allow more code to run on
Guile without modification, and will allow Guile hackers to produce
code compatible with other schemes. Help in this regard would be much
appreciated.


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@page
@node Concept Index
@unnumbered Concept Index

This index contains concepts, keywords and non-Schemey names for several
features, to make it easier to locate the desired sections.

@printindex cp

@page
@node Procedure Index
@unnumbered Procedure Index

@c FIXME::martin: Review me!

This is an alphabetical list of all the procedures and macros in Guile.

When looking for a particular procedure, please look under its Scheme
name as well as under its C name.  The C name can be constructed from
the Scheme names by a simple transformation described in the section
@xref{API Overview}.

@printindex fn

@page
@node Variable Index
@unnumbered Variable Index

@c FIXME::martin: Review me!

This is an alphabetical list of all the important variables and
constants in Guile.

When looking for a particular variable or constant, please look under
its Scheme name as well as under its C name.  The C name can be
constructed from the Scheme names by a simple transformation described
in the section @xref{API Overview}.

@printindex vr

@page
@node Type Index
@unnumbered Type Index

This is an alphabetical list of all the important data types defined in
the Guile Programmers Manual.

@printindex tp


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2010
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node Introduction
@chapter Introduction

Guile is an implementation of the Scheme programming language.  Scheme
(@url{schemers.org}) is an elegant and conceptually simple dialect of
Lisp, originated by Guy Steele and Gerald Sussman, and since evolved
by the series of reports known as RnRS (the
@tex
Revised$^n$
@end tex
@ifnottex
Revised^n
@end ifnottex
Reports on Scheme).

Unlike -- for example -- Python or Perl, Scheme has no benevolent
dictator.  There are many Scheme implementations, with different
characteristics and with communities and academic activities around
them, and the language develops as a result of the interplay between
these.  Guile's particular characteristics are that

@itemize
@item
it is easy to combine with other code written in C
@item
it has a historical and continuing connection with the GNU Project
@item
it emphasizes interactive and incremental programming
@item
it actually supports several languages, not just Scheme.
@end itemize

@noindent
The next few sections explain what we mean by these points.  The sections after
that cover how you can obtain and install Guile, and the typographical
conventions that we use in this manual.

@menu
* Guile and Scheme::
* Combining with C::
* Guile and the GNU Project::
* Interactive Programming::
* Supporting Multiple Languages::
* Obtaining and Installing Guile::
* Organisation of this Manual::
* Typographical Conventions::
@end menu

@node Guile and Scheme
@section Guile and Scheme

Guile implements Scheme as described in the
@tex
Revised$^5$
@end tex
@ifnottex
Revised^5
@end ifnottex
Report on the Algorithmic Language Scheme (usually known as
@acronym{R5RS}), providing clean and general data and control
structures.  Guile goes beyond the rather austere language presented
in @acronym{R5RS}, extending it with a module system, full access to
@acronym{POSIX} system calls, networking support, multiple threads,
dynamic linking, a foreign function call interface, powerful string
processing, and many other features needed for programming in the real
world.

The Scheme community has recently agreed and published R6RS, the
latest installment in the RnRS series.  R6RS significantly expands the
core Scheme language, and standardises many non-core functions that
implementations -- including Guile -- have previously done in
different ways.  Guile has been updated to incorporate some of the
features of R6RS, and to adjust some existing features to conform to
the R6RS specification, but it is by no means a complete R6RS
implementation. @xref{R6RS Support}.

Between R5RS and R6RS, the SRFI process (@url{http://srfi.schemers.org/})
standardised interfaces for many practical needs, such as multithreaded
programming and multidimensional arrays.  Guile supports many SRFIs, as
documented in detail in @ref{SRFI Support}.

In summary, so far as relationship to the Scheme standards is
concerned, Guile is an R5RS implementation with many extensions, some
of which conform to SRFIs or to the relevant parts of R6RS.

@node Combining with C
@section Combining with C Code

Like a shell, Guile can run interactively --- reading expressions from the user,
evaluating them, and displaying the results --- or as a script interpreter,
reading and executing Scheme code from a file.  Guile also provides an object
library, @dfn{libguile}, that allows other applications to easily incorporate a
complete Scheme interpreter.  An application can then use Guile as an extension
language, a clean and powerful configuration language, or as multi-purpose
``glue'', connecting primitives provided by the application.  It is easy to call
Scheme code from C code and vice versa, giving the application designer full
control of how and when to invoke the interpreter.  Applications can add new
functions, data types, control structures, and even syntax to Guile, creating a
domain-specific language tailored to the task at hand, but based on a robust
language design.

This kind of combination is helped by four aspects of Guile's design
and history.  First is that Guile has always been targeted as an
extension language.  Hence its C API has always been of great
importance, and has been developed accordingly.  Second and third are
rather technical points -- that Guile uses conservative garbage
collection, and that it implements the Scheme concept of continuations
by copying and reinstating the C stack -- but whose practical
consequence is that most existing C code can be glued into Guile as
is, without needing modifications to cope with strange Scheme
execution flows.  Last is the module system, which helps extensions to
coexist without stepping on each others' toes.

Guile's module system allows one to break up a large program into
manageable sections with well-defined interfaces between them.
Modules may contain a mixture of interpreted and compiled code; Guile
can use either static or dynamic linking to incorporate compiled code.
Modules also encourage developers to package up useful collections of
routines for general distribution; as of this writing, one can find
Emacs interfaces, database access routines, compilers, @acronym{GUI}
toolkit interfaces, and @acronym{HTTP} client functions, among others.

@node Guile and the GNU Project
@section Guile and the GNU Project

Guile was conceived by the GNU Project following the fantastic success
of Emacs Lisp as an extension language within Emacs.  Just as Emacs
Lisp allowed complete and unanticipated applications to be written
within the Emacs environment, the idea was that Guile should do the
same for other GNU Project applications.  This remains true today.

The idea of extensibility is closely related to the GNU project's
primary goal, that of promoting software freedom.  Software freedom
means that people receiving a software package can modify or enhance
it to their own desires, including in ways that may not have occurred
at all to the software's original developers.  For programs written in
a compiled language like C, this freedom covers modifying and
rebuilding the C code; but if the program also provides an extension
language, that is usually a much friendlier and lower-barrier-of-entry
way for the user to start making their own changes.

Guile is now used by GNU project applications such as AutoGen, Lilypond, Denemo,
Mailutils, TeXmacs and Gnucash, and we hope that there will be many more in
future.

@node Interactive Programming
@section Interactive Programming

Non-free software has no interest in its users being able to see how it works.
They are supposed to just accept it, or to report problems and hope that the
source code owners will choose to work on them.

Free software aims to work reliably just as much as non-free software does, but
it should also empower its users by making its workings available.  This is
useful for many reasons, including education, auditing and enhancements, as well
as for debugging problems.

The ideal free software system achieves this by making it easy for interested
users to see the source code for a feature that they are using, and to follow
through that source code step-by-step, as it runs.  In Emacs, good examples of
this are the source code hyperlinks in the help system, and @code{edebug}.
Then, for bonus points and maximising the ability for the user to experiment
quickly with code changes, the system should allow parts of the source code to
be modified and reloaded into the running program, to take immediate effect.

Guile is designed for this kind of interactive programming, and this
distinguishes it from many Scheme implementations that instead prioritise
running a fixed Scheme program as fast as possible --- because there are
tradeoffs between performance and the ability to modify parts of an already
running program.  There are faster Schemes than Guile, but Guile is a GNU
project and so prioritises the GNU vision of programming freedom and
experimentation.

@node Supporting Multiple Languages
@section Supporting Multiple Languages

Since the 2.0 release, Guile's architecture supports compiling any language to
its core virtual machine bytecode, and Scheme is just one of the supported
languages.  Other supported languages are Emacs Lisp, ECMAScript (commonly known
as Javascript) and Brainfuck, and work is under discussion for Lua, Ruby and
Python.

This means that users can program applications which use Guile in the language
of their choice, rather than having the tastes of the application's author
imposed on them.

@node Obtaining and Installing Guile
@section Obtaining and Installing Guile

Guile can be obtained from the main GNU archive site
@url{ftp://ftp.gnu.org} or any of its mirrors.  The file will be named
guile-@var{version}.tar.gz.  The current version is @value{VERSION}, so the
file you should grab is:

@url{ftp://ftp.gnu.org/pub/gnu/guile/guile-@value{VERSION}.tar.gz}

To unbundle Guile use the instruction

@example
zcat guile-@value{VERSION}.tar.gz | tar xvf -
@end example

@noindent
which will create a directory called @file{guile-@value{VERSION}} with
all the sources.  You can look at the file @file{INSTALL} for detailed
instructions on how to build and install Guile, but you should be able
to just do

@example
cd guile-@value{VERSION}
./configure
make
make install
@end example

This will install the Guile executable @file{guile}, the Guile library
@file{libguile} and various associated header files and support libraries. It
will also install the Guile reference manual.

@c [[include instructions for getting R5RS]]

Since this manual frequently refers to the Scheme ``standard'', also
known as R5RS, or the
@tex
``Revised$^5$ Report on the Algorithmic Language Scheme'',
@end tex
@ifnottex
``Revised^5 Report on the Algorithmic Language Scheme'',
@end ifnottex
we have included the report in the Guile distribution; see
@ref{Top, , Introduction, r5rs, Revised(5) Report on the Algorithmic
Language Scheme}.
This will also be installed in your info directory.

@node Organisation of this Manual
@section Organisation of this Manual

The rest of this manual is organised into the following chapters.

@table @strong
@item Chapter 2: Hello Guile!
A whirlwind tour shows how Guile can be used interactively and as
a script interpreter, how to link Guile into your own applications,
and how to write modules of interpreted and compiled code for use with
Guile.  Everything introduced here is documented again and in full by
the later parts of the manual.

@item Chapter 3: Hello Scheme!
For readers new to Scheme, this chapter provides an introduction to the basic
ideas of the Scheme language.  This material would apply to any Scheme
implementation and so does not make reference to anything Guile-specific.

@item Chapter 4: Programming in Scheme
Provides an overview of programming in Scheme with Guile.  It covers how to
invoke the @code{guile} program from the command-line and how to write scripts
in Scheme.  It also introduces the extensions that Guile offers beyond standard
Scheme.

@item Chapter 5: Programming in C
Provides an overview of how to use Guile in a C program.  It
discusses the fundamental concepts that you need to understand to
access the features of Guile, such as dynamic types and the garbage
collector.  It explains in a tutorial like manner how to define new
data types and functions for the use by Scheme programs.

@item Chapter 6: Guile API Reference
This part of the manual documents the Guile @acronym{API} in
functionality-based groups with the Scheme and C interfaces presented
side by side.

@item Chapter 7: Guile Modules
Describes some important modules, distributed as part of the Guile
distribution, that extend the functionality provided by the Guile
Scheme core.

@item Chapter 8: GOOPS
Describes GOOPS, an object oriented extension to Guile that provides
classes, multiple inheritance and generic functions.

@end table

@node Typographical Conventions
@section Typographical Conventions

We use some conventions in this manual.

@itemize @bullet

@item
For some procedures, notably type predicates, we use ``iff'' to mean
``if and only if''.  The construct is usually something like: `Return
@var{val} iff @var{condition}', where @var{val} is usually
``@nicode{#t}'' or ``non-@nicode{#f}''.  This typically means that
@var{val} is returned if @var{condition} holds, and that @samp{#f} is
returned otherwise.  To clarify: @var{val} will @strong{only} be
returned when @var{condition} is true.
@cindex iff

@item
In examples and procedure descriptions and all other places where the
evaluation of Scheme expression is shown, we use some notation for
denoting the output and evaluation results of expressions.

The symbol @samp{@result{}} is used to tell which value is returned by
an evaluation:

@lisp
(+ 1 2)
@result{} 3
@end lisp

Some procedures produce some output besides returning a value.  This
is denoted by the symbol @samp{@print{}}.

@lisp
(begin (display 1) (newline) 'hooray)
@print{} 1
@result{} hooray
@end lisp

As you can see, this code prints @samp{1} (denoted by
@samp{@print{}}), and returns @code{hooray} (denoted by
@samp{@result{}}).

@c Add other conventions here.

@end itemize

@c Local Variables:
@c TeX-master: "guile.texi"
@c End:


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2010
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node General Libguile Concepts
@section General concepts for using libguile

When you want to embed the Guile Scheme interpreter into your program or
library, you need to link it against the @file{libguile} library
(@pxref{Linking Programs With Guile}).  Once you have done this, your C
code has access to a number of data types and functions that can be used
to invoke the interpreter, or make new functions that you have written
in C available to be called from Scheme code, among other things.

Scheme is different from C in a number of significant ways, and Guile
tries to make the advantages of Scheme available to C as well.  Thus, in
addition to a Scheme interpreter, libguile also offers dynamic types,
garbage collection, continuations, arithmetic on arbitrary sized
numbers, and other things.

The two fundamental concepts are dynamic types and garbage collection.
You need to understand how libguile offers them to C programs in order
to use the rest of libguile.  Also, the more general control flow of
Scheme caused by continuations needs to be dealt with.

Running asynchronous signal handlers and multi-threading is known to C
code already, but there are of course a few additional rules when using
them together with libguile.

@menu
* Dynamic Types::               Dynamic Types.
* Garbage Collection::          Garbage Collection.
* Control Flow::                Control Flow.
* Asynchronous Signals::        Asynchronous Signals
* Multi-Threading::             Multi-Threading
@end menu

@node Dynamic Types
@subsection Dynamic Types

Scheme is a dynamically-typed language; this means that the system
cannot, in general, determine the type of a given expression at compile
time.  Types only become apparent at run time.  Variables do not have
fixed types; a variable may hold a pair at one point, an integer at the
next, and a thousand-element vector later.  Instead, values, not
variables, have fixed types.

In order to implement standard Scheme functions like @code{pair?} and
@code{string?} and provide garbage collection, the representation of
every value must contain enough information to accurately determine its
type at run time.  Often, Scheme systems also use this information to
determine whether a program has attempted to apply an operation to an
inappropriately typed value (such as taking the @code{car} of a string).

Because variables, pairs, and vectors may hold values of any type,
Scheme implementations use a uniform representation for values --- a
single type large enough to hold either a complete value or a pointer
to a complete value, along with the necessary typing information.

In Guile, this uniform representation of all Scheme values is the C type
@code{SCM}.  This is an opaque type and its size is typically equivalent
to that of a pointer to @code{void}.  Thus, @code{SCM} values can be
passed around efficiently and they take up reasonably little storage on
their own.

The most important rule is: You never access a @code{SCM} value
directly; you only pass it to functions or macros defined in libguile.

As an obvious example, although a @code{SCM} variable can contain
integers, you can of course not compute the sum of two @code{SCM} values
by adding them with the C @code{+} operator.  You must use the libguile
function @code{scm_sum}.

Less obvious and therefore more important to keep in mind is that you
also cannot directly test @code{SCM} values for trueness.  In Scheme,
the value @code{#f} is considered false and of course a @code{SCM}
variable can represent that value.  But there is no guarantee that the
@code{SCM} representation of @code{#f} looks false to C code as well.
You need to use @code{scm_is_true} or @code{scm_is_false} to test a
@code{SCM} value for trueness or falseness, respectively.

You also can not directly compare two @code{SCM} values to find out
whether they are identical (that is, whether they are @code{eq?} in
Scheme terms).  You need to use @code{scm_is_eq} for this.

The one exception is that you can directly assign a @code{SCM} value to
a @code{SCM} variable by using the C @code{=} operator.

The following (contrived) example shows how to do it right.  It
implements a function of two arguments (@var{a} and @var{flag}) that
returns @var{a}+1 if @var{flag} is true, else it returns @var{a}
unchanged.

@example
SCM
my_incrementing_function (SCM a, SCM flag)
@{
  SCM result;

  if (scm_is_true (flag))
    result = scm_sum (a, scm_from_int (1));
  else
    result = a;

  return result;
@}
@end example

Often, you need to convert between @code{SCM} values and appropriate C
values.  For example, we needed to convert the integer @code{1} to its
@code{SCM} representation in order to add it to @var{a}.  Libguile
provides many function to do these conversions, both from C to
@code{SCM} and from @code{SCM} to C.

The conversion functions follow a common naming pattern: those that make
a @code{SCM} value from a C value have names of the form
@code{scm_from_@var{type} (@dots{})} and those that convert a @code{SCM}
value to a C value use the form @code{scm_to_@var{type} (@dots{})}.

However, it is best to avoid converting values when you can.  When you
must combine C values and @code{SCM} values in a computation, it is
often better to convert the C values to @code{SCM} values and do the
computation by using libguile functions than to the other way around
(converting @code{SCM} to C and doing the computation some other way).

As a simple example, consider this version of
@code{my_incrementing_function} from above:

@example
SCM
my_other_incrementing_function (SCM a, SCM flag)
@{
  int result;

  if (scm_is_true (flag))
    result = scm_to_int (a) + 1;
  else
    result = scm_to_int (a);

  return scm_from_int (result);
@}
@end example

This version is much less general than the original one: it will only
work for values @var{A} that can fit into a @code{int}.  The original
function will work for all values that Guile can represent and that
@code{scm_sum} can understand, including integers bigger than @code{long
long}, floating point numbers, complex numbers, and new numerical types
that have been added to Guile by third-party libraries.

Also, computing with @code{SCM} is not necessarily inefficient.  Small
integers will be encoded directly in the @code{SCM} value, for example,
and do not need any additional memory on the heap.  See @ref{Data
Representation} to find out the details.

Some special @code{SCM} values are available to C code without needing
to convert them from C values:

@multitable {Scheme value} {C representation}
@item Scheme value @tab C representation
@item @nicode{#f}  @tab @nicode{SCM_BOOL_F}
@item @nicode{#t}  @tab @nicode{SCM_BOOL_T}
@item @nicode{()}  @tab @nicode{SCM_EOL}
@end multitable

In addition to @code{SCM}, Guile also defines the related type
@code{scm_t_bits}.  This is an unsigned integral type of sufficient
size to hold all information that is directly contained in a
@code{SCM} value.  The @code{scm_t_bits} type is used internally by
Guile to do all the bit twiddling explained in @ref{Data Representation}, but
you will encounter it occasionally in low-level user code as well.

@node Garbage Collection
@subsection Garbage Collection

As explained above, the @code{SCM} type can represent all Scheme values.
Some values fit entirely into a @code{SCM} value (such as small
integers), but other values require additional storage in the heap (such
as strings and vectors).  This additional storage is managed
automatically by Guile.  You don't need to explicitly deallocate it
when a @code{SCM} value is no longer used.

Two things must be guaranteed so that Guile is able to manage the
storage automatically: it must know about all blocks of memory that have
ever been allocated for Scheme values, and it must know about all Scheme
values that are still being used.  Given this knowledge, Guile can
periodically free all blocks that have been allocated but are not used
by any active Scheme values.  This activity is called @dfn{garbage
collection}.

It is easy for Guile to remember all blocks of memory that it has
allocated for use by Scheme values, but you need to help it with finding
all Scheme values that are in use by C code.

You do this when writing a SMOB mark function, for example
(@pxref{Garbage Collecting Smobs}).  By calling this function, the
garbage collector learns about all references that your SMOB has to
other @code{SCM} values.

Other references to @code{SCM} objects, such as global variables of type
@code{SCM} or other random data structures in the heap that contain
fields of type @code{SCM}, can be made visible to the garbage collector
by calling the functions @code{scm_gc_protect} or
@code{scm_permanent_object}.  You normally use these functions for long
lived objects such as a hash table that is stored in a global variable.
For temporary references in local variables or function arguments, using
these functions would be too expensive.

These references are handled differently: Local variables (and function
arguments) of type @code{SCM} are automatically visible to the garbage
collector.  This works because the collector scans the stack for
potential references to @code{SCM} objects and considers all referenced
objects to be alive.  The scanning considers each and every word of the
stack, regardless of what it is actually used for, and then decides
whether it could possibly be a reference to a @code{SCM} object.  Thus,
the scanning is guaranteed to find all actual references, but it might
also find words that only accidentally look like references.  These
`false positives' might keep @code{SCM} objects alive that would
otherwise be considered dead.  While this might waste memory, keeping an
object around longer than it strictly needs to is harmless.  This is why
this technique is called ``conservative garbage collection''.  In
practice, the wasted memory seems to be no problem.

The stack of every thread is scanned in this way and the registers of
the CPU and all other memory locations where local variables or function
parameters might show up are included in this scan as well.

The consequence of the conservative scanning is that you can just
declare local variables and function parameters of type @code{SCM} and
be sure that the garbage collector will not free the corresponding
objects.

However, a local variable or function parameter is only protected as
long as it is really on the stack (or in some register).  As an
optimization, the C compiler might reuse its location for some other
value and the @code{SCM} object would no longer be protected.  Normally,
this leads to exactly the right behavior: the compiler will only
overwrite a reference when it is no longer needed and thus the object
becomes unprotected precisely when the reference disappears, just as
wanted.

There are situations, however, where a @code{SCM} object needs to be
around longer than its reference from a local variable or function
parameter.  This happens, for example, when you retrieve some pointer
from a smob and work with that pointer directly.  The reference to the
@code{SCM} smob object might be dead after the pointer has been
retrieved, but the pointer itself (and the memory pointed to) is still
in use and thus the smob object must be protected.  The compiler does
not know about this connection and might overwrite the @code{SCM}
reference too early.

To get around this problem, you can use @code{scm_remember_upto_here_1}
and its cousins.  It will keep the compiler from overwriting the
reference.  For a typical example of its use, see @ref{Remembering
During Operations}.

@node Control Flow
@subsection Control Flow

Scheme has a more general view of program flow than C, both locally and
non-locally.

Controlling the local flow of control involves things like gotos, loops,
calling functions and returning from them.  Non-local control flow
refers to situations where the program jumps across one or more levels
of function activations without using the normal call or return
operations.

The primitive means of C for local control flow is the @code{goto}
statement, together with @code{if}.  Loops done with @code{for},
@code{while} or @code{do} could in principle be rewritten with just
@code{goto} and @code{if}.  In Scheme, the primitive means for local
control flow is the @emph{function call} (together with @code{if}).
Thus, the repetition of some computation in a loop is ultimately
implemented by a function that calls itself, that is, by recursion.

This approach is theoretically very powerful since it is easier to
reason formally about recursion than about gotos.  In C, using
recursion exclusively would not be practical, though, since it would eat
up the stack very quickly.  In Scheme, however, it is practical:
function calls that appear in a @dfn{tail position} do not use any
additional stack space (@pxref{Tail Calls}).

A function call is in a tail position when it is the last thing the
calling function does.  The value returned by the called function is
immediately returned from the calling function.  In the following
example, the call to @code{bar-1} is in a tail position, while the
call to @code{bar-2} is not.  (The call to @code{1-} in @code{foo-2}
is in a tail position, though.)

@lisp
(define (foo-1 x)
  (bar-1 (1- x)))

(define (foo-2 x)
  (1- (bar-2 x)))
@end lisp

Thus, when you take care to recurse only in tail positions, the
recursion will only use constant stack space and will be as good as a
loop constructed from gotos.

Scheme offers a few syntactic abstractions (@code{do} and @dfn{named}
@code{let}) that make writing loops slightly easier.

But only Scheme functions can call other functions in a tail position:
C functions can not.  This matters when you have, say, two functions
that call each other recursively to form a common loop.  The following
(unrealistic) example shows how one might go about determining whether a
non-negative integer @var{n} is even or odd.

@lisp
(define (my-even? n)
  (cond ((zero? n) #t)
        (else (my-odd? (1- n)))))

(define (my-odd? n)
  (cond ((zero? n) #f)
        (else (my-even? (1- n)))))
@end lisp

Because the calls to @code{my-even?} and @code{my-odd?} are in tail
positions, these two procedures can be applied to arbitrary large
integers without overflowing the stack.  (They will still take a lot
of time, of course.)

However, when one or both of the two procedures would be rewritten in
C, it could no longer call its companion in a tail position (since C
does not have this concept).  You might need to take this
consideration into account when deciding which parts of your program
to write in Scheme and which in C.

In addition to calling functions and returning from them, a Scheme
program can also exit non-locally from a function so that the control
flow returns directly to an outer level.  This means that some functions
might not return at all.

Even more, it is not only possible to jump to some outer level of
control, a Scheme program can also jump back into the middle of a
function that has already exited.  This might cause some functions to
return more than once.

In general, these non-local jumps are done by invoking
@dfn{continuations} that have previously been captured using
@code{call-with-current-continuation}.  Guile also offers a slightly
restricted set of functions, @code{catch} and @code{throw}, that can
only be used for non-local exits.  This restriction makes them more
efficient.  Error reporting (with the function @code{error}) is
implemented by invoking @code{throw}, for example.  The functions
@code{catch} and @code{throw} belong to the topic of @dfn{exceptions}.

Since Scheme functions can call C functions and vice versa, C code can
experience the more general control flow of Scheme as well.  It is
possible that a C function will not return at all, or will return more
than once.  While C does offer @code{setjmp} and @code{longjmp} for
non-local exits, it is still an unusual thing for C code.  In
contrast, non-local exits are very common in Scheme, mostly to report
errors.

You need to be prepared for the non-local jumps in the control flow
whenever you use a function from @code{libguile}: it is best to assume
that any @code{libguile} function might signal an error or run a pending
signal handler (which in turn can do arbitrary things).

It is often necessary to take cleanup actions when the control leaves a
function non-locally.  Also, when the control returns non-locally, some
setup actions might be called for.  For example, the Scheme function
@code{with-output-to-port} needs to modify the global state so that
@code{current-output-port} returns the port passed to
@code{with-output-to-port}.  The global output port needs to be reset to
its previous value when @code{with-output-to-port} returns normally or
when it is exited non-locally.  Likewise, the port needs to be set again
when control enters non-locally.

Scheme code can use the @code{dynamic-wind} function to arrange for
the setting and resetting of the global state.  C code can use the
corresponding @code{scm_internal_dynamic_wind} function, or a
@code{scm_dynwind_begin}/@code{scm_dynwind_end} pair together with
suitable 'dynwind actions' (@pxref{Dynamic Wind}).

Instead of coping with non-local control flow, you can also prevent it
by erecting a @emph{continuation barrier}, @xref{Continuation
Barriers}.  The function @code{scm_c_with_continuation_barrier}, for
example, is guaranteed to return exactly once.

@node Asynchronous Signals
@subsection Asynchronous Signals

You can not call libguile functions from handlers for POSIX signals, but
you can register Scheme handlers for POSIX signals such as
@code{SIGINT}.  These handlers do not run during the actual signal
delivery.  Instead, they are run when the program (more precisely, the
thread that the handler has been registered for) reaches the next
@emph{safe point}.

The libguile functions themselves have many such safe points.
Consequently, you must be prepared for arbitrary actions anytime you
call a libguile function.  For example, even @code{scm_cons} can contain
a safe point and when a signal handler is pending for your thread,
calling @code{scm_cons} will run this handler and anything might happen,
including a non-local exit although @code{scm_cons} would not ordinarily
do such a thing on its own.

If you do not want to allow the running of asynchronous signal handlers,
you can block them temporarily with @code{scm_dynwind_block_asyncs}, for
example.  See @xref{System asyncs}.

Since signal handling in Guile relies on safe points, you need to make
sure that your functions do offer enough of them.  Normally, calling
libguile functions in the normal course of action is all that is needed.
But when a thread might spent a long time in a code section that calls
no libguile function, it is good to include explicit safe points.  This
can allow the user to interrupt your code with @key{C-c}, for example.

You can do this with the macro @code{SCM_TICK}.  This macro is
syntactically a statement.  That is, you could use it like this:

@example
while (1)
  @{
    SCM_TICK;
    do_some_work ();
  @}
@end example

Frequent execution of a safe point is even more important in multi
threaded programs, @xref{Multi-Threading}.

@node Multi-Threading
@subsection Multi-Threading

Guile can be used in multi-threaded programs just as well as in
single-threaded ones.

Each thread that wants to use functions from libguile must put itself
into @emph{guile mode} and must then follow a few rules.  If it doesn't
want to honor these rules in certain situations, a thread can
temporarily leave guile mode (but can no longer use libguile functions
during that time, of course).

Threads enter guile mode by calling @code{scm_with_guile},
@code{scm_boot_guile}, or @code{scm_init_guile}.  As explained in the
reference documentation for these functions, Guile will then learn about
the stack bounds of the thread and can protect the @code{SCM} values
that are stored in local variables.  When a thread puts itself into
guile mode for the first time, it gets a Scheme representation and is
listed by @code{all-threads}, for example.

Threads in guile mode can block (e.g., do blocking I/O) without causing any
problems@footnote{In Guile 1.8, a thread blocking in guile mode would prevent
garbage collection to occur.  Thus, threads had to leave guile mode whenever
they could block.  This is no longer needed with Guile 2.0.}; temporarily
leaving guile mode with @code{scm_without_guile} before blocking slightly
improves GC performance, though.  For some common blocking operations, Guile
provides convenience functions.  For example, if you want to lock a pthread
mutex while in guile mode, you might want to use @code{scm_pthread_mutex_lock}
which is just like @code{pthread_mutex_lock} except that it leaves guile mode
while blocking.

All libguile functions are (intended to be) robust in the face of
multiple threads using them concurrently.  This means that there is no
risk of the internal data structures of libguile becoming corrupted in
such a way that the process crashes.

A program might still produce nonsensical results, though.  Taking
hashtables as an example, Guile guarantees that you can use them from
multiple threads concurrently and a hashtable will always remain a valid
hashtable and Guile will not crash when you access it.  It does not
guarantee, however, that inserting into it concurrently from two threads
will give useful results: only one insertion might actually happen, none
might happen, or the table might in general be modified in a totally
arbitrary manner.  (It will still be a valid hashtable, but not the one
that you might have expected.)  Guile might also signal an error when it
detects a harmful race condition.

Thus, you need to put in additional synchronizations when multiple
threads want to use a single hashtable, or any other mutable Scheme
object.

When writing C code for use with libguile, you should try to make it
robust as well.  An example that converts a list into a vector will help
to illustrate.  Here is a correct version:

@example
SCM
my_list_to_vector (SCM list)
@{
  SCM vector = scm_make_vector (scm_length (list), SCM_UNDEFINED);
  size_t len, i;

  len = SCM_SIMPLE_VECTOR_LENGTH (vector);
  i = 0;
  while (i < len && scm_is_pair (list))
    @{
      SCM_SIMPLE_VECTOR_SET (vector, i, SCM_CAR (list));
      list = SCM_CDR (list);
      i++;
    @}

  return vector;
@}
@end example

The first thing to note is that storing into a @code{SCM} location
concurrently from multiple threads is guaranteed to be robust: you don't
know which value wins but it will in any case be a valid @code{SCM}
value.

But there is no guarantee that the list referenced by @var{list} is not
modified in another thread while the loop iterates over it.  Thus, while
copying its elements into the vector, the list might get longer or
shorter.  For this reason, the loop must check both that it doesn't
overrun the vector (@code{SCM_SIMPLE_VECTOR_SET} does no range-checking)
and that it doesn't overrung the list (@code{SCM_CAR} and @code{SCM_CDR}
likewise do no type checking).

It is safe to use @code{SCM_CAR} and @code{SCM_CDR} on the local
variable @var{list} once it is known that the variable contains a pair.
The contents of the pair might change spontaneously, but it will always
stay a valid pair (and a local variable will of course not spontaneously
point to a different Scheme object).

Likewise, a simple vector such as the one returned by
@code{scm_make_vector} is guaranteed to always stay the same length so
that it is safe to only use SCM_SIMPLE_VECTOR_LENGTH once and store the
result.  (In the example, @var{vector} is safe anyway since it is a
fresh object that no other thread can possibly know about until it is
returned from @code{my_list_to_vector}.)

Of course the behavior of @code{my_list_to_vector} is suboptimal when
@var{list} does indeed get asynchronously lengthened or shortened in
another thread.  But it is robust: it will always return a valid vector.
That vector might be shorter than expected, or its last elements might
be unspecified, but it is a valid vector and if a program wants to rule
out these cases, it must avoid modifying the list asynchronously.

Here is another version that is also correct:

@example
SCM
my_pedantic_list_to_vector (SCM list)
@{
  SCM vector = scm_make_vector (scm_length (list), SCM_UNDEFINED);
  size_t len, i;

  len = SCM_SIMPLE_VECTOR_LENGTH (vector);
  i = 0;
  while (i < len)
    @{
      SCM_SIMPLE_VECTOR_SET (vector, i, scm_car (list));
      list = scm_cdr (list);
      i++;
    @}

  return vector;
@}
@end example

This version uses the type-checking and thread-robust functions
@code{scm_car} and @code{scm_cdr} instead of the faster, but less robust
macros @code{SCM_CAR} and @code{SCM_CDR}.  When the list is shortened
(that is, when @var{list} holds a non-pair), @code{scm_car} will throw
an error.  This might be preferable to just returning a half-initialized
vector.

The API for accessing vectors and arrays of various kinds from C takes a
slightly different approach to thread-robustness.  In order to get at
the raw memory that stores the elements of an array, you need to
@emph{reserve} that array as long as you need the raw memory.  During
the time an array is reserved, its elements can still spontaneously
change their values, but the memory itself and other things like the
size of the array are guaranteed to stay fixed.  Any operation that
would change these parameters of an array that is currently reserved
will signal an error.  In order to avoid these errors, a program should
of course put suitable synchronization mechanisms in place.  As you can
see, Guile itself is again only concerned about robustness, not about
correctness: without proper synchronization, your program will likely
not be correct, but the worst consequence is an error message.

Real thread-safeness often requires that a critical section of code is
executed in a certain restricted manner.  A common requirement is that
the code section is not entered a second time when it is already being
executed.  Locking a mutex while in that section ensures that no other
thread will start executing it, blocking asyncs ensures that no
asynchronous code enters the section again from the current thread,
and the error checking of Guile mutexes guarantees that an error is
signalled when the current thread accidentally reenters the critical
section via recursive function calls.

Guile provides two mechanisms to support critical sections as outlined
above.  You can either use the macros
@code{SCM_CRITICAL_SECTION_START} and @code{SCM_CRITICAL_SECTION_END}
for very simple sections; or use a dynwind context together with a
call to @code{scm_dynwind_critical_section}.

The macros only work reliably for critical sections that are
guaranteed to not cause a non-local exit.  They also do not detect an
accidental reentry by the current thread.  Thus, you should probably
only use them to delimit critical sections that do not contain calls
to libguile functions or to other external functions that might do
complicated things.

The function @code{scm_dynwind_critical_section}, on the other hand,
will correctly deal with non-local exits because it requires a dynwind
context.  Also, by using a separate mutex for each critical section,
it can detect accidental reentries.


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node Linking Guile with Libraries
@section Linking Guile with Libraries

The previous section has briefly explained how to write programs that
make use of an embedded Guile interpreter.  But sometimes, all you
want to do is make new primitive procedures and data types available
to the Scheme programmer.  Writing a new version of @code{guile} is
inconvenient in this case and it would in fact make the life of the
users of your new features needlessly hard.

For example, suppose that there is a program @code{guile-db} that is a
version of Guile with additional features for accessing a database.
People who want to write Scheme programs that use these features would
have to use @code{guile-db} instead of the usual @code{guile} program.
Now suppose that there is also a program @code{guile-gtk} that extends
Guile with access to the popular Gtk+ toolkit for graphical user
interfaces.  People who want to write GUIs in Scheme would have to use
@code{guile-gtk}.  Now, what happens when you want to write a Scheme
application that uses a GUI to let the user access a database?  You
would have to write a @emph{third} program that incorporates both the
database stuff and the GUI stuff.  This might not be easy (because
@code{guile-gtk} might be a quite obscure program, say) and taking this
example further makes it easy to see that this approach can not work in
practice.

It would have been much better if both the database features and the GUI
feature had been provided as libraries that can just be linked with
@code{guile}.  Guile makes it easy to do just this, and we encourage you
to make your extensions to Guile available as libraries whenever
possible.

You write the new primitive procedures and data types in the normal
fashion, and link them into a shared library instead of into a
stand-alone program.  The shared library can then be loaded dynamically
by Guile.

@menu
* A Sample Guile Extension::
@end menu

@node A Sample Guile Extension
@subsection A Sample Guile Extension

This section explains how to make the Bessel functions of the C library
available to Scheme.  First we need to write the appropriate glue code
to convert the arguments and return values of the functions from Scheme
to C and back.  Additionally, we need a function that will add them to
the set of Guile primitives.  Because this is just an example, we will
only implement this for the @code{j0} function.

Consider the following file @file{bessel.c}.

@smallexample
#include <math.h>
#include <libguile.h>

SCM
j0_wrapper (SCM x)
@{
  return scm_make_real (j0 (scm_num2dbl (x, "j0")));
@}

void
init_bessel ()
@{
  scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
@}
@end smallexample

This C source file needs to be compiled into a shared library.  Here is
how to do it on GNU/Linux:

@smallexample
gcc -shared -o libguile-bessel.so -fPIC bessel.c
@end smallexample

For creating shared libraries portably, we recommend the use of GNU
Libtool (@pxref{Top, , Introduction, libtool, GNU Libtool}).

A shared library can be loaded into a running Guile process with the
function @code{load-extension}.  In addition to the name of the
library to load, this function also expects the name of a function from
that library that will be called to initialize it.  For our example,
we are going to call the function @code{init_bessel} which will make
@code{j0_wrapper} available to Scheme programs with the name
@code{j0}.  Note that we do not specify a filename extension such as
@file{.so} when invoking @code{load-extension}.  The right extension for
the host platform will be provided automatically.

@lisp
(load-extension "libguile-bessel" "init_bessel")
(j0 2)
@result{} 0.223890779141236
@end lisp

For this to work, @code{load-extension} must be able to find
@file{libguile-bessel}, of course.  It will look in the places that
are usual for your operating system, and it will additionally look
into the directories listed in the @code{LTDL_LIBRARY_PATH}
environment variable.

To see how these Guile extensions via shared libraries relate to the
module system, @xref{Putting Extensions into Modules}.

@c Local Variables:
@c TeX-master: "guile.texi"
@c End:


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2010
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node Linking Programs With Guile
@section Linking Programs With Guile

This section covers the mechanics of linking your program with Guile
on a typical POSIX system.

The header file @code{<libguile.h>} provides declarations for all of
Guile's functions and constants.  You should @code{#include} it at the
head of any C source file that uses identifiers described in this
manual.  Once you've compiled your source files, you need to link them
against the Guile object code library, @code{libguile}.

On most systems, you should not need to tell the compiler and linker
explicitly where they can find @file{libguile.h} and @file{libguile}.
When Guile has been installed in a peculiar way, or when you are on a
peculiar system, things might not be so easy and you might need to pass
additional @code{-I} or @code{-L} options to the compiler.  Guile
provides the utility program @code{guile-config} to help you find the
right values for these options.  You would typically run
@code{guile-config} during the configuration phase of your program and
use the obtained information in the Makefile.

@menu
* Guile Initialization Functions::  What to call first.
* A Sample Guile Main Program::  Sources and makefiles.
@end menu

@node Guile Initialization Functions
@subsection Guile Initialization Functions

To initialize Guile, you can use one of several functions.  The first,
@code{scm_with_guile}, is the most portable way to initialize Guile.  It
will initialize Guile when necessary and then call a function that you
can specify.  Multiple threads can call @code{scm_with_guile}
concurrently and it can also be called more than once in a given thread.
The global state of Guile will survive from one call of
@code{scm_with_guile} to the next.  Your function is called from within
@code{scm_with_guile} since the garbage collector of Guile needs to know
where the stack of each thread is.

A second function, @code{scm_init_guile}, initializes Guile for the
current thread.  When it returns, you can use the Guile API in the
current thread.  This function employs some non-portable magic to learn
about stack bounds and might thus not be available on all platforms.

One common way to use Guile is to write a set of C functions which
perform some useful task, make them callable from Scheme, and then link
the program with Guile.  This yields a Scheme interpreter just like
@code{guile}, but augmented with extra functions for some specific
application --- a special-purpose scripting language.

In this situation, the application should probably process its
command-line arguments in the same manner as the stock Guile
interpreter.  To make that straightforward, Guile provides the
@code{scm_boot_guile} and @code{scm_shell} function.

For more about these functions, see @ref{Initialization}.

@node A Sample Guile Main Program
@subsection A Sample Guile Main Program

Here is @file{simple-guile.c}, source code for a @code{main} and an
@code{inner_main} function that will produce a complete Guile
interpreter.

@example
/* simple-guile.c --- how to start up the Guile
   interpreter from C code.  */

/* Get declarations for all the scm_ functions.  */
#include <libguile.h>

static void
inner_main (void *closure, int argc, char **argv)
@{
  /* module initializations would go here */
  scm_shell (argc, argv);
@}

int
main (int argc, char **argv)
@{
  scm_boot_guile (argc, argv, inner_main, 0);
  return 0; /* never reached */
@}
@end example

The @code{main} function calls @code{scm_boot_guile} to initialize
Guile, passing it @code{inner_main}.  Once @code{scm_boot_guile} is
ready, it invokes @code{inner_main}, which calls @code{scm_shell} to
process the command-line arguments in the usual way.

Here is a Makefile which you can use to compile the above program.  It
uses @code{guile-config} to learn about the necessary compiler and
linker flags.
@example
# Use GCC, if you have it installed.
CC=gcc

# Tell the C compiler where to find <libguile.h>
CFLAGS=`guile-config compile`

# Tell the linker what libraries to use and where to find them.
LIBS=`guile-config link`

simple-guile: simple-guile.o
        $@{CC@} simple-guile.o $@{LIBS@} -o simple-guile

simple-guile.o: simple-guile.c
        $@{CC@} -c $@{CFLAGS@} simple-guile.c
@end example

If you are using the GNU Autoconf package to make your application more
portable, Autoconf will settle many of the details in the Makefile above
automatically, making it much simpler and more portable; we recommend
using Autoconf with Guile.  Guile also provides the @code{GUILE_FLAGS}
macro for autoconf that performs all necessary checks.  Here is a
@file{configure.in} file for @code{simple-guile} that uses this macro.
Autoconf can use this file as a template to generate a @code{configure}
script.  In order for Autoconf to find the @code{GUILE_FLAGS} macro, you
will need to run @code{aclocal} first (@pxref{Invoking aclocal,,,
automake, GNU Automake}).

@example
AC_INIT(simple-guile.c)

# Find a C compiler.
AC_PROG_CC

# Check for Guile
GUILE_FLAGS

# Generate a Makefile, based on the results.
AC_OUTPUT(Makefile)
@end example

Here is a @code{Makefile.in} template, from which the @code{configure}
script produces a Makefile customized for the host system:
@example
# The configure script fills in these values.
CC=@@CC@@
CFLAGS=@@GUILE_CFLAGS@@
LIBS=@@GUILE_LDFLAGS@@

simple-guile: simple-guile.o
        $@{CC@} simple-guile.o $@{LIBS@} -o simple-guile
simple-guile.o: simple-guile.c
        $@{CC@} -c $@{CFLAGS@} simple-guile.c
@end example

The developer should use Autoconf to generate the @file{configure}
script from the @file{configure.in} template, and distribute
@file{configure} with the application.  Here's how a user might go about
building the application:

@example
$ ls
Makefile.in     configure*      configure.in    simple-guile.c
$ ./configure
creating cache ./config.cache
checking for gcc... (cached) gcc
checking whether the C compiler (gcc  ) works... yes
checking whether the C compiler (gcc  ) is a cross-compiler... no
checking whether we are using GNU C... (cached) yes
checking whether gcc accepts -g... (cached) yes
checking for Guile... yes
creating ./config.status
creating Makefile
$ make
[...]
$ ./simple-guile
guile> (+ 1 2 3)
6
guile> (getpwnam "jimb")
#("jimb" "83Z7d75W2tyJQ" 4008 10 "Jim Blandy" "/u/jimb"
  "/usr/local/bin/bash")
guile> (exit)
$
@end example

@c Local Variables:
@c TeX-master: "guile.texi"
@c End: