Simple C-Extension example

This example shows how to create a C-Extension library on Linux® using gcc.

Note: The command line options used in this sample to compile and link shared libraries are for a Linux operating system.

The "splitext.c" C interface file

#include "f2c/fglExt.h"

int next_token(int);

UsrFunction usrFunctions[]={
  { "next_token", next_token, 1, 2, 0 },
  { 0,0,0,0,0 }
};

The "split.c" file

#include <string.h>
#include <assert.h>
#include "f2c/fglExt.h"

int next_token( int in_num );
int next_token( int in_num )
{
       char src[2049];
       char *p;
       assert(in_num == 1);
       popvchar(src, sizeof(src));
       if (*src == '\0') {
           pushvchar("", 0);
           pushvchar("", 0);
       } else {
           p = strchr(src, ' ');
           if (p == NULL) {
               pushvchar(src, strlen(src));
               pushvchar("", 0);
           } else {
               *p = '\0';
               pushvchar(src, strlen(src));
               p++;
               pushvchar(p, strlen(p));
           }
       }
       return 2;
}

The program "split.4gl"

IMPORT libsplit
MAIN
    DEFINE t, r STRING -- Or VARCHAR(100)
    LET r = "This is my first C Extension"
    WHILE TRUE
        CALL next_token(r) RETURNING t, r
        IF t IS NULL THEN
            EXIT WHILE
        END IF
        DISPLAY "token: ", t
    END WHILE
END MAIN

Compiling and running the sample

Compile the C Module and the C interface file:

$ gcc -c -I $FGLDIR/include -fPIC split.c
$ gcc -c -I $FGLDIR/include -fPIC splitext.c
Create the shared library:
$ gcc -shared -o libsplit.so split.o splitext.o -L$FGLDIR/lib -lfgl
It is also possible to use the fglmkext utility as follows:
fglmkext -o libsplit.so split.c splitext.c
Compile the .4gl module:
$ fglcomp split.4gl
Run the sample:
$ fglrun split.42m
token: This
token: is
token: my
token: first
token: C
token: Extension