Calling C from CLIPS

In this blog post, we will outline how to call a C function from CLIPS. Doing so allows us to connect CLIPS with other programs through C.


First, we must revisit the CLIPS 6.30 folder that we installed CLIPS with in my previous “Interfacing CLIPS with C++” post. Change directories to the /clips/ folder inside. From here we can locate the userfunctions.c file, where we will write our C functions into CLIPS.

Writing a Function

At first, userfunctions.c will only contain two methods: void UserFunctions(), and void EnvUserFunctions(void *theEnv). In the EnvUserFunctions method, we can declare our functions. For example, if we were to write a method to find the area of a triangle, our EnvUserFunctions method would look something like this:

void EnvUserFunctions(void *theEnv) {
  extern double area(void *);
  EnvDefineFunction(theEnv, "area", 'd', PTIEF area, "area");

extern double area(void *) declares the method in C. EnvDefineFunction(theEnv, , , , ) declares the method in CLIPS as a command. We then write the area method in the userfunctions.c file:

double area(void *environment) {
  double base, height;
  if(EnvArgCountCheck(environment, "area", EXACTLY, 2) == -1) return (-1.0);//checks for exactly 2 arguments
  base = EnvRtnDouble(environment, 1);//reads in a double as input
  height = EnvRtnDouble(environment, 2); //reads the second double
  return (0.5 * base * height);

For a more detailed explanation on writing user functions in CLIPS, consult pages 39-54 of the Advanced Programming Guide.

Recompiling CLIPS

Now that we have our desired user functions, change directories back to main CLIPS 6.30 folder, and type the following commands:

$ ./configure
$ make
$ sudo make install

Provided that there are no syntax errors in your userfunctions.c file, CLIPS should compile correctly. We can test to see if everything works correctly through terminal:

$ clips
         CLIPS (Quicksilver Beta 5/31/08)
CLIPS> (area 5.0 10.0)
CLIPS> (area 90.0 60.0)

Example code for two methods, one void and one double, can be found here: