graphics.h in gcc (plus kbhit() and getch() too!)

November 7, 2008

After migrating completely to Ubuntu, one of the things I didn’t appreciate was that my old graphics.h programs (which I spent many a long hour on) didn’t work here, for gcc did not have support for those primitive graphics.

I found today (from another blog) that there exists a library to do the trick. To quote the specific library’s man page, “libgraph –  library providing the TurboC graphics API (a.k.a graphics.h) in Linux using SDL.” Exactly what I was looking for!

I reproduce (almost exactly) the content of that blog post:

1) Install the following in Synaptic Package Manager

libsdl-image1.2
libsdl-image1.2-dev
guile-1.8
guile-1.8-dev
libsdl1.2debian-arts
libartsc0-dev
libaudiofile-dev
libesd0-dev
libdirectfb-dev
libdirectfb-extra
libfreetype6-dev
libxext-dev
x11proto-xext-dev
libfreetype6(upgrade)
libaa1
libaa1-dev
libslang2-dev
libasound2
libasound-dev

Actually, only the first 4 need be checked for installation, the rest get included as dependencies. But just in case, confirm that all of the above are getting installed.

The above process removes some packages, but that’s fine. Unfortunately for some reason, many other important packages of mine got removed, but things are ok (till now).

2)  Download and install libgraph-1.0.1 using:

./configure
sudo make
sudo make install

3) Include graphics.h in your C file. Initialize the graphics system by:

int gd=DETECT, gm=VGAMAX;
initgraph(&gd, &gm, NULL);

4) Compile your program using g++ with the argument -lgraph

5) The error “./a.out: error while loading shared libraries: libgraph.so.1: cannot open shared object file: No such file or directory” can be solved by

sudo cp /usr/local/lib/libgraph.* /usr/lib

Interestingly, the function getch() (which is very useful to a novice programmer) is also a part of this graphics.h. When porting my old programs to gcc, I used to comment out the getch() (which, frankly, I used to overuse). So one more problem solved!

I also needed the functionality of kbhit() (another useful function for the novice Turbo C programmer). Google is truly great, I found this.

Edit: For a better implementation of getch(), read about the ncurses library here.