`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

- Use the `import` statement to load your extension module from Go. For example:

  >     import "example"

- C functions work just like Go functions. However, the function names are automatically capitalized in order to make the names visible from other Go packages. For example:

  >     g := example.Gcd(42,105)

  (If there are name conflicts, you can use the `%rename` directive in the .i file or the `-rename` option to Go to rename one or the other symbol).
- C global variables are accessed using getter and setter functions. The getter function is named `Get` followed by the capitalized name of the C variable. The Setter function uses `Set` instead of `Get`.

  >     a = example.GetFoo()