SWIG/Examples/go/simple/

Simple Go Example

This example illustrates how you can hook Go to a very simple C program containing a function and a global variable.

The C Code

Suppose you have the following C code:
/* File : example.c */

/* A global variable */
double Foo = 3.0;

/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
  int g;
  g = y;
  while (x > 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
}

The SWIG interface

Here is a simple SWIG interface file:
/* File: example.i */
%module example

extern int gcd(int x, int y);
extern double Foo;

Compilation

These are the instructions if you are using 6g/8g rather than gccgo.
  1. Run swig -go example.i. This will create the three files example.go, example_gc.c, and example_wrap.c.
  2. Compile example.go using 6g or 8g; e.g., 6g example.go.
  3. Compile example_gc.c using 6c or 8c; e.g., 6c example_gc.c.
  4. Put the two object files together into an archive named example.a; e.g., gopack grc example.a example.6 example_gc.6.
  5. Compile the example_wrap.c file using your standard C compiler with the -fpic option; e.g., gcc -c -O -fpic example_wrap.c.
  6. Also compile the actual code, not generated by SWIG; e.g., gcc -c -O -fpic example.c.
  7. Put the gcc compiled object files into a shared library; e.g., gcc -shared -o example.so example_wrap.o example.o.
  8. Compile the program which demonstrates how to use the library; e.g., 6g runme.go.
  9. Link the program; e.g., 6l -o runme runme.6.
  10. Now you should have a program runme.

Using the extension

The Go program which demonstrates calling the C functions from Go is runme.go.

Key points