![](/file/12652/www.mactech.com.tar/www.mactech.com/sites/all/themes/custom_front/images/you_are_here_red.gif)
![](/file/12652/www.mactech.com.tar/www.mactech.com/sites/default/files/beta-site.gif)
|
Volume Number: 19 (2003)
Issue Number: 9
Column Tag: Review: Ch
Ch - A C/C++ Interpreter
New possibilities for people who like C and Unix.
by Matt Campbell
First Look
Given that C is the basis for much of the programming behind the Mac, which now utilizes Unix as its substructure, C seems to be the language that all Macs speak. If you're not eager to dive into many different languages for different tasks, take a look at Ch. Ch expands the capabilities of C and makes it an interpreted language. Its tight integration with the Unix shell makes it natural for Mac OS X. To those who are using C and are comfortable with the command line interface or are willing to learn, I think you will discover Ch to be a useful tool. Ch can help with shell programming, development, numerical computing, and learning C.
Setup and Trying It Out
Anyone wanting to give it a whirl can get the Standard version of Ch for OS X, Unix, and Linux free. Not bad for starters. Check out the website at http://www.softintegration.com/. Go to the downloads page and register, after which you will be sent download instructions via email (mine came in a matter of seconds). After downloading and installing the package, start the Terminal application in the Applications > Utilities folder and type ch -d. The -d option loads the startup file, .chrc, in your home directory. Then edit this file using vi and uncomment the line that starts with _path. This lets you run files on the command line without entering the current directory path, './', before the file name. There's a little information in the README file including directions to uninstall. If you like, Ch can even be run as your default shell. Using the Terminal > Preferences... menu, select the button to execute this command upon creating a terminal window and enter /bin/ch. Now any new shell you start will automatically be running Ch. More documentation can be found in the /usr/local/ch/docs folder from the command line by typing open filename.pdf. I've been using Ch for 6 months and C covers lots of ground, so I'll try to give you the run down on most of the important features of Ch. Here it goes.
Ch as a C/C++ Interpreter
At the simplest level, Ch is a C interpreter. It is able to run C code without compiling. It does not need a project space or any of the other associated files that are usually created in the compile/build/debug/execute cycle by most programs used in writing code. All that's necessary is the program file. There are two levels in its ability to run the C language on the fly. First, it will run C code interactively from the command line, as a command interpreter. If you're still learning C, this is invaluable. When having problems with a particular statement or wondering about the output of a command, it can be entered on the command line to test how it works. This works not only for simple assignment statements, but loops and conditional statements as well. It is sort of "programming as you go" when coupled with the Terminal's drag and drop ability. You can test several lines of code and if they work properly, just drop them in your program. Second, programs can be executed from the command line without compiling, with Ch acting as a program interpreter. Many people like this option for testing out small pieces of code or being able to run programs in stages, testing new functions as you build them into the program. The process of the compile/debug cycle can be skipped altogether. This allows for fast changes to a program and quick concept testing. A nice feature of Ch comes up when running programs this way. It's error messages are not the cryptic type usually given by a compiler when a program has problems. When the program fails, Ch prints out the offending line and line number and also points to the suspected error with arrows. Most of the time, I find this feature speeds the process of correcting small errors and oversights since you don't have to pick through a lot of lines to find where the problems are hiding. As an example of interpretive C, here's the classic "hello world" program run in four ways. First is the actual program:
#include <stdio.h> int main() { printf("\nhello world.\n\n"); }
Figure 1. Ch shell running hello.c as an Interpreter
Figure 1 above shows the first method, the program being run by typing the name at the command prompt. Ch uses '>' as the default prompt. Along with the program file, you just need any associated header files and library files if you programmed them separately. Below are the other ways. In the second, the command is interpreted directly and executed. Third, the same thing is done with C++ code. More about that in the next section. The fourth way is the simplest. All that is needed is quotes and Ch interprets this as a string.
Interpreting C code on the command line:
> printf("hello world.") hello world. C++ interpreted: > cout << "hello world." << endl hello world.
Interpreting a string directly:
> "hello world" hello world
This is another example of code executed on the command line. Here I actually defined a simple function and then used it as you normally would inside a program.
> void input(void){char a[20],b[20];scanf("%s",a); scanf("%s",b);printf("\n%s\n",strcat(a,b));} > input() Mac Tech MacTech
In addition, the two methods of interpreting C can be combined. Programs can be run from the command line with . program.c (that's a period followed by a space then the program name) in the current shell. The functions used in the program will remain loaded in memory after the program is run. Then they can by used interactively on the command line. This works great for more complex functions that you'd like to try out. Class definitions and all the related member functions for C++ code work the same way. All the member functions can be tested interactively. By running an empty program that includes any necessary header files, all the functions can be tested without having to write a program that uses them. I like being able to try out functions this way to help me visualize program flow. The parse shell command is similar. Used for debugging, parse program.c checks for syntax errors and keeps functions loaded in memory without running the program. Variables have to be declared in the shell; drag and drop works nicely here. Once created though, they can be used in function calls just as in a program. Return values from functions can even be passed back and assigned to variables in the shell.
Ch is not just for simple programs; it can handle larger ones. When studying Dynamics recently, I used a program called Autolev that symbolically formulated the equations of motion of a system of bodies and then wrote a C program that numerically solved the resulting differential equations. In my particular case, I sought to simulate the simplified kicking motion of a person. Autolev wrote a program that came ion at over a thousand lines, including the recursive numerical functions. Ch ran the program without any problems and without the need to go to a compiler. The best part was that with only slight modifications, I was able to get visual output in the form of graphs by adding just a little bit of code. I'll have an example of graphing in Ch a little later. This was great because not only was the feedback immediate, but it also kept me from having to import my data from multiple output files into a spreadsheet every time I ran the simulation.
Supporting C90/C99/C++ Standards
The ability to run C interpretively is nice. Add to this the fact that Ch is built to completely encompass the C90 standard, the standard that most C code is based on, and you have a good place to develop code. Ch goes beyond this, adding functionality to C by bringing in some of the newest standards, borrowing ideas from other programming languages, and blending in new functions to enhance C. Ch adds in many useful features from the new standard for C, C99. In keeping up with the times, Ch supports complex and long long type variables, floating point arithmetic, variable length arrays, polymorphism for generic functions, binary type output for printf statements, and the // comment style. Most of the new standards that are supported in Ch are those that help in writing code for numerical computing. Along this same line, Ch has added some practical features from C++. It supports classes with public and private members, reference type and pass-by-reference, and the cout, cin, and cerr functions to name some of the main ones. Thus, object oriented programming is possible without having to go completely to the C++ language. As C++ does not necessarily support all the newest features of the C99 standard, Ch becomes a mixture of the two, combining some features of both. The following is a simple program that uses classes. Immediately after it, you can see where I used the . classes.cpp syntax, both running the program and loading the classes into memory. I then used the class definition and functions on the command line.
// test uses of class #include <iostream.h> class Triangle { public: Triangle(double, double); void hypotenuse(); private: double m, n, h; }; int main() { class Triangle t1 = Triangle(3, 4); t1.hypotenuse(); class Triangle t2 = Triangle(5, 12); t2.hypotenuse(); return 0; } Triangle::Triangle(double a, double b) { m = a; n = b; } void Triangle::hypotenuse() { h = sqrt((m*m) + (n*n)); cout << "Geometry of a Right Triangle" << endl; cout << "Sides = " << m << " and " << n << endl; cout << "Hypotenuse = " << h << "\n" << endl; } // End of file > . classes.cpp Geometry of a Right Triangle Sides = 3.0000 and 4.0000 Hypotenuse = 5.0000 Geometry of a Right Triangle Sides = 5.0000 and 12.0000 Hypotenuse = 13.0000 > class Triangle t1 = Triangle(2, 3) > t1.hypotenuse() Geometry of a Right Triangle Sides = 2.0000 and 3.0000 Hypotenuse = 3.6056
New Data Types & Features
String_t type
Ch also comes with new data types and functions. Strings have been promoted to a first class object using a new data type, string_t. This type automatically handles memory allocation as needed, frees used memory when appropriate, and allows strings to be used in symbolic computing. Strings can also be used to control the number of iterations in a loop. A foreach loop has been added, which breaks a string into tokens and runs through the loop once for each token, as demonstrated below. This function has a man page within Ch.
/* Using the foreach loop */ #include <stdio.h> int main() { string_t loop, token; loop = "this string has been broken up"; foreach(token; loop) printf("%s\n", token); return 0; } // End of file > loop.c this string has been broken up
As with strings, arrays can be used in new ways as well. Assumed shape arrays, name[:][:], are allowed in function calls where the shape of the array is not determined until run time. Array subscripts can be declared explicitly, meaning that the first element of an array can be element 1 or even -1, instead of 0.
Computational Array Type
Computational arrays have been added as a new data type, array type name[m][n], which allows them to be treated as a first class object. These can be thought of as matrices and vectors for use in calculations. This is where the numerical part of Ch really shines. In C, arrays have to be handled with many levels of embedded loops. In Ch, conversely, the solution to a matrix equation or printing an array can often be done with one line. Output statements can have matrix equations as arguments and print them as if they were single numbers. Matrix math can be done as simply as floating-point math. Array_1 * Array_2 will perform the matrix multiplication according to the rules of Linear Algebra. The '.*' operator multiplies corresponding elements of two arrays times one another. Generic math functions also work with the new data type. The following is an example of computational array type, how it can be passed to functions, and using it for computations and output without loops.
/* matrix calculations in Ch */ #include <stdio.h> #include <array.h> array double function(array double [:][:], array double [:][:], int)[:][:]; int main() { array double A1[3][2] = {1, 2, 3, 4, 5, 6}; array double A2[2][2] = {1, 2, 4, 5}; array double B1[4][2] = {1, 3, 5, 7, 10, 11, 12, 13}; array double B2[2][2] = {7, 8, 3, 6}; int C1 = 1, C2 = 5; printf("\nPart 1:\n%3g", function(A1, B1, C1)); printf("\nPart 2:\n%4g", function(A2, B2, C2)); return 0; } array double function(array double a[:][:], array double b[:][:], int c)[:][:] { return c * (a .* a) * transpose(b); } // End of file > matrix.c Part 1: 13 33 54 64 57 157 266 316 133 377 646 768 Part 2: 195 135 1560 990
Here, similar arrays and functions are interpreted on the command line:
> array int x[6] > array int y[6] > linspace(x,1,6) 6 > x 1 2 3 4 5 6 > y 0 0 0 0 0 0 > void add(array int *p, array int *q){q=p+p;} > void square(array int *s, array int *t) {t=s.*s;printf("s=\n%d\nt=\n%d\n",s,t);} > add(x,y) > y 2 4 6 8 10 12 > square(x,y) s= 1 2 3 4 5 6 t= 1 4 9 16 25 36 > y 1 4 9 16 25 36
New functions have been added in Ch to aid in using computational arrays, most of which are for numerical computing. This allows for complex computations to be done in C without going to another math program. Unfortunately, Ch does not include the ability to do symbolic manipulations, nor does it have the depth of numerical functions that some professional level math programs have, but the most important computations can be handled numerically. Statistics, data analysis, Fourier transforms, vector algebra, integration, and differentiation are just a few of the computational algorithms that have been included. They are available in the header file numeric.h. Most of the matrix manipulations used in Linear Algebra, such as transpose, inverse, or more complicated ones, can be done as demonstrated in the example above.
Using computational arrays, an array of reference can be passed to a function, which can handle multiple data types and different dimensions. One function can be given much more flexibility this way. Functions can also return computational arrays of varying dimensions, making it easy to give values back to the calling function. The shape() function is a simple way to get array dimensions when using an array of reference since its size is not passed. Shown here with both computational and C arrays, it returns the dimensions of the argument. By using it twice, you can get the total number of dimensions.
> array double a[5][6] > shape(a) 5 6 > shape(shape(a)) 2 > double b[20] > shape(b) 20
Two & Three Dimensional Plotting
As a compliment to the increased numerical capabilities, Ch has also added high level plotting through function calls that look and feel like C. Both 2-D and 3-D plots can be implemented with simple function calls, or through a class designed to handle plotting named CPlot. The plotting functions, e.g. plotxyz(), will accept all the default display options. The only arguments needed are two or three arrays, either computational or C arrays, with the correct number of points. You can add axis labels and a title with optional inputs. These functions are great for getting quick feedback by adding one line of extra code to a program. By using the CPlot class, many more options are available through the member functions. Data can be added in sets to allow for multiple curves or surfaces. Subplots can be generated that occupy the same window but use different data sets or are different types of plots. Plotting can be done to the screen or directed to a file with a specified type. I have found PNG files to be the most useful as they are read by Preview, but you can also output a postscript file if you use an application that will read them. There's quite a bit of flexibility given the relatively simple commands that are used. Plots can be rectangular, polar, cylindrical, or spherical. 2-D plots can be simple lines, steps, impulses, or points. 3-D surfaces can be drawn as a mesh, impulses, or points all with or without contours. The view orientation for 3-D plots can be changed. There are many more options available for graphs and demos of each can be found on the Softintegration website. Below, I've created two simple examples of plots done in Ch. Figure 2 was done on the command line.
> array double x[100] > array double y[100] > linspace(x, 0, 2*M_PI) 100 > y = sin(x) 0.0000 0.0634 0.1266 0.1893 0.2511 0.3120 0.3717 0.4298 0.4862 0.5406 0.5929 0.6428 0.6901 0.7346 0.7761 0.8146 0.8497 0.8815 0.9096 0.9341 0.9549 0.9718 0.9848 0.9938 0.9989 0.9999 0.9969 0.9898 0.9788 0.9638 0.9450 0.9224 0.8960 0.8660 0.8326 0.7958 0.7557 0.7127 0.6668 0.6182 0.5671 0.5137 0.4582 0.4009 0.3420 0.2817 0.2203 0.1580 0.0951 0.0317 -0.0317 -0.0951 -0.1580 -0.2203 -0.2817 -0.3420 -0.4009 -0.4582 -0.5137 -0.5671 -0.6182 -0.6668 -0.7127 -0.7557 -0.7958 -0.8326 -0.8660 -0.8960 -0.9224 -0.9450 -0.9638 -0.9788 -0.9898 -0.9969 -0.9999 -0.9989 -0.9938 -0.9848 -0.9718 -0.9549 -0.9341 -0.9096 -0.8815 -0.8497 -0.8146 -0.7761 -0.7346 -0.6901 -0.6428 -0.5929 -0.5406 -0.4862 -0.4298 -0.3717 -0.3120 -0.2511 -0.1893 -0.1266 -0.0634 0.0000 > plotxy(x, y, "Sin(x)", "X", "Y") 0
Figure 2. Plotting Sine wave from command line
Figure 3 below shows the output of the plot.c program. Here plotting is done with the CPlot class.
/* plot.c */ /* 3D Plotting */ #include <stdio.h> #include <math.h> #include <chplot.h> # define NUMPTS 30 int main() { // Variables array double x[NUMPTS], y[NUMPTS], z1[NUMPTS*NUMPTS], z2[NUMPTS*NUMPTS]; array double levels[6]; int i, j; string_t xlabel = "x", ylabel = "y", zlabel = "z", title = "3D Surfaces"; class CPlot plot; // Create data for x, y, and levels arrays linspace(x, -1, 1); linspace(y, -1, 1); linspace(levels, -1, 1); // Computation of 2 surfaces for(i = 0; i < NUMPTS; i++) { for(j = 0; j < NUMPTS; j++) { z1[NUMPTS*i+j] = x[i]*x[i] + y[j]*y[j] - 1.0; z2[NUMPTS*i+j] = sin(6*x[i]) * sin(6*y[j]); } } // Enter arrays to class "plot" plot.data3D(x, y, z1); plot.data3D(x, y, z2); // Set options for graphing plot.changeViewAngle(60, 60); plot.contourMode(PLOT_CONTOUR_BASE); plot.contourLevels(levels); plot.title(title); plot.label(PLOT_AXIS_X, xlabel); plot.label(PLOT_AXIS_Y, ylabel); plot.label(PLOT_AXIS_Z, zlabel); // Graph results plot.plotting(); // Create output files for printing plot.outputType(PLOT_OUTPUTTYPE_FILE, "png color", "plot_file.png"); plot.plotting(); return 0; }
Figure 3. Two 3D surfaces from program plot.c
Command Shell & Shell Programming
Perhaps the most useful feature of Ch is its ability to run as a shell. You interface with Ch on the command line from within Terminal or the X11 application. It runs just like a Unix shell with all the same commands available. It can be started from within any of the shells that come with the Mac, be it bash, sh, csh, tcsh, or zch. You start it by typing ch at a command prompt. You can also start these other shells from within Ch, if you so desire. While this may mean no fancy interface with lots of buttons or menus, it's good news for the dedicated Unix users who like the fact that they can now wrap their hands around Unix on the Mac. To people unfamiliar with a Unix terminal, as I was a year ago, this is an opportunity to learn. I mean, who wouldn't want to know how to use the vi editor? You may not end up using the terminal as your primary interface for day to day work since the Aqua interface is much more human friendly, but no doubt you'll find it useful with the mass of information that's out there on the topic of everything Unix. If you end up using Ch regularly while running and testing code, you can make Ch the default shell used by Terminal, as mentioned in the Setup section. No need to run the default tcsh shell or any other shell at all. You can also save a Terminal file that runs Ch. Just set Ch as the default shell, open a new one, and set all your other preferences; then use Terminal's Save As command to store this shell for quick access from the Library menu.
The fact that Ch runs as a Unix shell has another significant meaning. While Ch will run scripts the same as any other shell, the fact that Ch is a C interpreter gives you have the ability to include C code in your scripts. Loops and conditional statements can use the more familiar C syntax. If the first line of the shell program is #!/bin/ch, you don't even need to be running Ch to be able to execute the script with included C code. To compliment this, scripts can be called and run directly from inside of a program. No special include function is necessary, just the script name and path, if it happens to be in a different folder. These features will give anyone more options when it comes to shell programming. Not having to learn another syntax for writing scripts is nice too. The script below, saved as scripting.ch, uses C right along side some regular shell programming.
#!/bin/ch #include <stdio.h> echo Sample script int i; for(i = 0; i < 3; i++) { printf("hello %d\n", i); } int transfer(void); echo Making copy of file cp ./test1.txt ./test3.txt echo Copying contents transfer(); echo moving new file mkdir ./testfolder mv ./test3.txt ./testfolder/test3.txt echo done! int transfer(void) { FILE *in, *out; char c; if(!(in = fopen("test2.txt", "r"))) { perror("_tmpfile"); return -1; } in = fopen("test2.txt","r"); out = fopen("test3.txt", "a"); while((c = fgetc(in)) != EOF) { fputc(c, out); }; echo Closing files fclose(in); fclose(out); return 0; } // End of file > scripting Sample script hello 0 hello 1 hello 2 Making copy of file Copying contents Closing files moving new file done!
Ch adds an additional feature to make running scripts and programs even simpler. If the file is named with the extension '.ch', it is not necessary to include the extension on the command line to run the script. It's automatically recognized as shown in the above example. At the prompt following the script, just typing the filename without the extension is enough to run it. As Ch runs programs interpretively, this works the same when running C programs too. The drawback here is that if you want to compile a program using a C or C++ compiler you will get an error unless you change the extension to '.c' or '.cpp'.
Easy interface with Existing C Library
Another nice feature coming out of the fact that Ch supports the current C standards is that you can use existing C libraries without modification under Ch. All of the existing tools that you've developed previously will not need to be rewritten as if you are transitioning to a new type of language. By utilizing the SDK package for Ch, even precompiled binaries can be included within Ch as in C.
Positive and Negative
So far I tried to cover all the features and positive things about Ch that I've run across in my personal experience using the program. To summarize, I like its tight fit with the Mac and OS X. Considering that the Ch interface is basically a shell and that the Mac now comes with utilities to provide access to Unix, they seem to compliment one another. I believe the power of Ch's interpretive nature will aid anyone in shell programming and writing C code. Built on the standards of C and expanding on them to bring more potential to the language ensures that it will always be a useful tool. Don't forget that the Standard version of Ch is free for Mac OS X (Linux and Unix too). This alone will provide anyone with a simple, clean interface for running C and C++ code. This version doesn't include the computational array type, added numeric functions, or plotting, but it's a fantastic way to learn C interactively. Just be prepared to learn some shell commands if you've never used a terminal interface before.
That being said, there are a few areas where Ch could stand some improvement. One of the first things you might notice is the lack of a Tab Complete feature at the command line interface. This is a handy thing to have when navigating the command line. In Ch, long file names, which I am a fan of, have to be typed out completely. Dragging and dropping files from the Finder to the Terminal window can save you some of this work because this includes the entire path. Unlike Unix, thankfully, Ch is not case sensitive and can handle spaces without quotes or backslashes when it comes to file and folders names. This makes it a little easier to navigate through the folders that might give you longer names when using Aqua. Still, Tab Complete is sorely missed when in a Ch shell. Another issue crops up with file permissions. When a new file is created with vi or another text editor, it is not set to be an executable file so Ch will not run it. This might be an inherent feature of Unix for security reasons. You need to modify your file with chmod 755 filename.c. This will make it executable to everyone. Ch will then run the file as I have in the above examples.
There is a lot of documentation that comes with Ch in the form of PDF files located in /usr/local/ch/docs. The Ch Users Guide is almost 700 pages and covers not just Ch but much of the C language in general and many Unix commands. Although very thorough, it's a plain, utilitarian document so, as with most manuals, it is not always easy to read. It does have a lot of useful information such as the summary of the most common shell and vi commands and comparisons between Ch and other languages. The Ch Reference Guide is close to 1000 pages and gives detailed information on many C and Ch functions found in the most common header files. Those with quite a bit of programming experience can probably sift through these documents and pull out the stuff they need quickly. Beginners might want a different book to show them the basics of C.
Perhaps the biggest disappointment with Ch for the Mac is the lack of any kind of copy/paste ability when it comes to graphing. As shown above, graphs are drawn inside new windows in X11. You can't copy or drag the graph from here. Screenshots seem impractical unless you use a slick screen capture program in lieu of Grab. I typically save graphs as PNG files from within the program and open them in Preview. This works well given all of Preview's export options, but it is still frustrating not being able to simply drag and drop the graph right from the window onto a document or copy and open it directly in Preview from the pasteboard. As this is a limitation of Unix and not Ch, it will not be changing anytime soon. It will only be another reminder of why we like the Mac interface so much. On the topic of graphing, Ch needs X windows in order to display graphs. The Ch website lists Xfree86 (XDarwin) with the OroborOSX window manager as system requirements. I have been using Apple's X11 (Beta 3) without any problems. The catch here is if you like using Terminal's more user friendly interface as opposed to the xterm in X11, you need to start the Terminal application from within X11, either through the Application menu or by modifying the ~/.xinitrc file. I actually learned how to do this in the "X11 Tweaks" article in the May 2003 issue of MacTech.
There's quite a bit of information here, but as this can't really cover it all effectively, I would urge anyone who's found this interesting to check out Softintegration's website. Aside from more information, example code is abundant. There is a Student version available and also a 30 day Demo for the Professional version. Scripting and numerical computing are definite strong points, but there are many other features to check out. Ch has to be the best and most intuitive way to learn the C language. Considering you can get a free simple tool to use the latest C standards interpretively, it's definitely worth a look.
Bibliography and References
Cheng, Harry H. The Ch Language Environment, User's Guide. Revision 3.7. SoftIntegration, Inc. Davis, 2003.
Morin, Rich. "X11 Tweaks". MacTech Magazine. 19:5 (May 2003), pp. 12-15.
http://www.softintegration.com/ - Homepage for Ch
POSTSCRIPT
Ch 4.0 was recently released. Starting with this version, Ch Standard Edition is freely available to everyone on all supported platforms. The Professional Edition is now free to all academic users for all platforms, giving them access to the computational and graphing features.
Matt Campbell is a Graduate Student in Mechanical Engineering at University of California, Davis. He has become a devoted Mac user over the past 2 years and has recently entered the world of programming. He hopes that more engineering apps will be developed for the Mac so he can finally convince his colleges that Macs are the way to go. Feel free to provide some feedback at mtycampbell@ucdavis.edu.
![](/file/12652/www.mactech.com.tar/www.mactech.com/sites/all/themes/custom_front/img/search_text.gif)
- SPREAD THE WORD:
- Slashdot
- Digg
- Del.icio.us
- Newsvine