Next: , Up: Init Snarfing


13.1.1 How c2x works

Usage: c2x [-o OUTFILE] [CPP-ARGS ...]

See guile-tools c2x, for details.

See Macros c2x recognizes, for a list of the special (some would say magic) cpp macros you can use.

For example, here is how you might define a new subr called clear-image, implemented by the C function clear_image:

     #include <libguile.h>
     
     SCM_DEFINE (clear_image, "clear-image", 1, 0, 0,
                 (SCM image_smob),
                 "Clear the image.")
     #define FUNC_NAME s_clear_image
     {
       /* C code to clear the image... */
     }
     #undef FUNC_NAME
     
     void
     init_image_type ()
     {
     #include "image-type.x"
     }

The SCM_DEFINE declaration says that the C function clear_image implements a Scheme subr called clear-image, which takes one required argument (type SCM named image_smob), no optional arguments, and no tail argument. See Doc Extraction from C Source, for info on the docstring.

This works in concert with FUNC_NAME to also define a static array of characters named s_clear_image, initialized to the string "clear-image". The body of clear_image may use the array in error messages, instead of writing out the literal string; this may save string space on some systems.

Assuming the text above lives in a file named image-type.c, you will need to execute the following command to prepare this file for compilation:

     guile-tools c2x -o image-type.x image-type.c

This scans image-type.c for SCM_DEFINE declarations, and writes to image-type.x the output:

     scm_make_gsubr (s_clear_image, 1, 0, 0, (SCM (*)() ) clear_image);

When compiled normally, SCM_DEFINE is a macro which expands to a declaration of the s_clear_image string.

Note that the output file name matches the #include from the input file. Also, you still need to provide all the same information you would if you were using scm_make_gsubr yourself, but you can place the information near the function definition itself, so it is less likely to become incorrect or out-of-date.

If you have many files that c2x must process, you should consider using a fragment like the following in your Makefile:

     snarfcppopts = $(DEFS) $(AM_CPPFLAGS) $(CPPFLAGS)
     SUFFIXES = .c .x
     .c.x:
             guile-tools c2x -o $@ $< $(snarfcppopts)

This tells make to run guile-tools c2x to produce each needed .x file from the corresponding .c file.

Aside from the required argument INFILE, c2x passes its command-line arguments directly to the C preprocessor, which it uses to extract the information it needs from the source code. this means you can pass normal compilation flags to c2x to define preprocessor symbols, add header file directories, and so on.