Some Frequently Asked Questions
Some Frequently Asked Questions about programming (updated)
The software links provided here to local copies of third-party software titles are provided
as a courtesy to students. The homepages for the software titles themselves may lead you to
more current versions. Some of the titles have become hard to find.
1 How do I compile a program?
2 After compiling, what do I do?
3 What do the file extensions .c, .cpp, .cc and so forth mean?
4 What is a header file?
5 How do I write a program?
6 I tried to compile a program and got ``/tmp/ccYAJGpb.o(.text+0x1e4d): undefined reference to sqrt'', what the hell does that mean?
7 What is optimization?
8 How can I redirect output into a file to capture it?
9 What are the differences between C, C++ and Java?
10 I have a FORTRAN77 program, how easy is it to convert it to C?
11 I have an old QBASIC program, can it be converted to C?
12 What about Java, can it be converted to C?
13 What about pascal, can it also be converted to C?
14 In English please, what is a pointer?
15 When I ran my program, i got ``segmentation fault'', what does that mean?
16 How can I pass a string to a function?
17 What is meant by a 16 or 32 bit compiler?
18 I want to compute some stuff to 100 decimal places, any suggestions?
19 How do I create or open a file for output or input?
20 I need to create many files for output, and want the names to be numbered, how can it be done simply?
21 I want my program to ask me which file I want to open, and then list all of the files in my working directory. How do I do it?
22 What are assertions, and can I override them if they are used in a program?
23 I tried to use a macro instead of a function to cut down overhead, and my program segfaults when I run it. What's wrong with it?
24 I am migrating to UNIX from the Borland Turbo-C compiler. Is there a UNIX version of the Borland conio console input-output library, and the Borland graphical interface?
25 I have an executable program for which I would like to have the source code. Can it be ``decompiled''?
26 I want to use assembly language in an inline function, but when I look at samples of assembly for Linux it looks completely different than the examples in my MASM or TASM assembly books. What is going on?
27 When I try to compile a program using some dynamically linked library that I just installed, I get a linker error ``/usr/i686-pc-linux-gnu/bin/ld: cannot find -lgrx'', how can I fix this?
28 When I try to compile a program, the compiler claims that some header or library cannot be found. Give me a simple fix.
29 I wrote a really useful program and compiled it on DOS, but it won't run on my Linux box. What can I do?
30 I wrote a simple program in C++, but a C compiler won't compile it. Why not?
31 I wrote a parallelized program using pthreads, but it is no faster than the non-parallel version, why not?
32 I think I might learn assembly language. Will that make my programs run faster?
33 I have a whole bunch of simple functions that I want to compile into a static library. How do I do it?
34 I have a whole bunch of simple functions that I want to compile into a dynamically linked library (dll). How do I do it?
35 I am sick of typing in those long compile lines, is there some way to automate compilations?
36 I used GOTO in BASIC and in FORTRAN77, but I never see it in C, how do I use GOTO in C?
37 I want to read in a certain number of bytes of data of unknown type into a buffer from some file, fscanf() can't do it. What should I use?
38 What is a structure, and how do I declare and initialize one?
39 What is a class in C++ or objective C?
40 Can C use complex numbers? How do I declare them?
41 I translated a matrix manipulation program from FORTRAN77 to C, and the FORTRAN77 version is a lot faster. How do I fix this?
42 How do I find a particular OpenSource program?
43 How do I install OpenSource software?
44 I think my program has a memory leak, how can I find it and eliminate it?
45 I want my program to be able to produce a PDF graphic. Are there any free PDF graphics libraries?
46 I never bother to properly indent my code and it looks like hell. Oh what shall I do?
47 Is there a basic interpreter for Xwindows with full xterm graphic support?
48 What about graphics support for FORTRAN, are there add-on libraries that offer graphics support?
49 How do I use random numbers in a C program? If I want to use randoms in FORTRAN77, do I have to write my own generator?
50 I really want to use the time/timer functions to initialize randoms and time processes. Gimme Gimme Gimme.
51 How does a class in C++ differ from C-structs?
52 What is operator and function overloading?
53 I wrote some nasty thang that left my machine littered with shared memory blocks and message queues, how can I clean it all up?
54 Java is too slow for my simulations, and my graphics flicker badly with my current C or FORTRAN graphics library. How can I double buffer them?
55 Why does pthread_create() only accept one stinkin datum as its operand? What good is that? Can't threads accept arrays of data?
56 My program uses libplot to create a graphic and write it to a file, but my program always segmentation faults near the end. Why?
57 I need a very basic Java applet template. Please.
58 What do I need to do to create and run Java applets in Netscape?
59 What do I need to do to create and run Java applications?
60 How do I pass command line parameters to my C program at runtime?
61 How do I pass command line parameters to my Java application at runtime?
62 I need an example of a simple Java applet illustrating layout and scrollbar use.
63 I need an example of a simple Java applet illustrating mouse event handling.
64 I need a WIN32 native compiler for C, C++ and FORTRAN77, but I am cheap and would rather profit from the hard work of others than part from any of my beautiful money. Oh what shall become of me?
65 I am reading in a data file, its length will vary, and I need to detect some end-of-file condition, how is that done?
66 In BASIC I can make my simulation respond to keystrokes, but in C on UNIX the translated program simply halts on getch() and sits there waiting. Why, and how can I change this?
67 I have legacy code written in ALGOL, is there an ALGOL to C translator?
68 How do I compile an executable for a WIN32 machine on a LINUX computer?
69 I need to be able to create many temporary files, with different names. How can this be done as simply as possible?
1 How do I compile a program?
Compilation is converting the actual text for the program code into machine language, which is an executable object. Actual compilation by invocation of the compiler is compiler specific. Suppose your program is called program.c. On my machine I can create an executable called program by typing
gcc -o program program.c
on the console command line. On a DOS machine with the Borland Turbo-C compiler, it might be
C:\TC\bin\tc program.c
and on a Sun SparcStation 10 it would be
cc -o program program.c
2 After compiling, what do I do?
You run the program. This amounts to typing
./program
on a Linux machine, or if you are on a DOS computer
program.exe
The kernel will then execute your program.
3 What do the file extensions .c, .cpp, .cc and so forth mean?
These are extensions used to determine what type of file the code represents. Most C programs should end in .c, a C++ program on my machine should end in .cc, and on a Borland Turbo-C machine it should be .cpp. A FORTRAN77 program should end in .f, an x86 assembly program should end in .s. Object files are files compiled to machine language by the compiler, and end in .o. A static library archive such as the math library will end in .a, and a dynamically loaded library will end in .so. Some compiler will choke if your file does not end in the correct extension.
4 What is a header file?
In C and C++ we often dramatically cut down the size of a program by using external libraries, and preprocessor directives to include a header file that declares all of the functions in the library. A statement such as #include < math.h > in a program tells the C preprocessor to include all of the function prototypes and declarations in the header file math.h, located in a central place such as /usr/include, in the program at compile time. Thats all that the header contains. If you create your own libraries, you will need to write header files for them containing declaration and prototyping lines.
5 How do I write a program?
The first step is to start up a text editor, such as vi or xemacs on a UNIX machine, or notepad on a WIN32 machine. You could use the DOS edit program as well. Now just type in your code. Save it with the correct file extension as ASCII text. Do not let the editor format it, if you do the compiler will not recognize it as a program text.
6 I tried to compile a program and got ``/tmp/ccYAJGpb.o(.text+0x1e4d): undefined reference to sqrt'', what the hell does that mean?
The compiler puts all of the objects that it creates in the /tmp directory
temporarily. If the linker fails to link your program with a library that you thought that you used, you get a message like this. This is a sign that you forgot to link your code to the library at compile time. To manually link to the math library in C, use
gcc -o program program.c -lm
If you link to multiple libraries, such as the multiple precision library, and the parallel thread library, you might need something like
gcc -D_REENTRANT -o program program.c -lm -lgmp -lpthread
7 What is optimization?
Some good modern compilers will rewrite your code on the fly at compile time in a way that maximizes performance. Highly optimized C can be as fast as hand-written assembly code. You can compile with optimization levels 1-6 with the -ON switch, for example optimization level 3;
gcc -O3 -o program program.c -lm
I usually compile -O6 -funroll-loops -fomit-frame-pointer -march=pentiumpro to specify loop unrolling (an old and venerable optimization trick to ``fatten'' a loop) and to specify X686 architecture enhancements.
8 How can I redirect output into a file to capture it?
Use data redirection; on both UNIX and DOS machines you can dump output into a file called data for example by
./program > data
and on Linux you could even pipe this into a graphics routine to plot it on the fly with
./program | graph -T X
Data redirection is quick and dirty, you can save your output without writing the code to create and write to a file.
9 What are the differences between C, C++ and Java?
At the procedural programming level, there are almost no syntactical differences. If you learn one of these, you can quickly pick up another, and pretty easily convert simple procedural programs from one language to another. C and C++ are about 40-100 times faster than Java, since they are compiled, and Java is interpreted like BASIC.
Java does not have pointers. This is good because pointers have the potential to introduce subtle bugs into a program. This is bad because pointers are perhaps the single most powerful programming construction. Take your pick.
10 I have a FORTRAN77 program, how easy is it to convert it to C?
Pretty damn simple; get the f2c converter. This is free from www.netlib.org at Oakridge National Laboratories.
or local copy . Simply type
f2c program.f program.c
it does a great job of rewriting the code in C.
11 I have an old QBASIC program, can it be converted to C?
There is a program qb2c-3.2k.tgz available from the devel directory of
ftp://sunsite.unc.edu/pub/Linux/ or local copy that can be used to convert quick BASIC, which is the version of BASIC shipped with DOS and WIN-3.1, into C code.
This package is actually much more than a translator; it will actually allow you to run any QBASIC program, even those with graphics, within an Xwindow. It also has many new graphics routines for X. Essentially it is a complete BASIC compiler solution for UNIX, giving you the ability to use BASIC as a compiled programming language on the UNIX platform. I have been able to get many old TRUBASIC programs to run exceptionally fast with this program.
To convert a BASIC program to C, and then compile it if it has X graphics calls;
bcc program.bas
gcc -L/usr/X11R6/lib -L./ -o program program.c -lX11 -lqbX11 -lm
You may find this particularly useful if you take physics 303. The only caveat is that the standard BASIC language rules regarding keyword capitalization must be obeyed. Qb2c comes with an extensive manual that should be carefully consulted.
Here is a simple example, a TRUBASIC program rewritten to use qb2c win.bas
12 What about Java, can it be converted to C?
The toba and j2c translators should be able to do this. The latest gcc C compiler can compile Java into working bytecode using the gjc frontend.
13 What about pascal, can it also be converted to C?
Of course; get the p2c translator from www.netlib.org or ftp://sunsite.unc.edu/pub/Linux/devel. There is also the freepascal and gpc free pascal compilers. Search the library at www.appwatch.com for these.
You might try pascaltoc , but I do not know if it works well or not.
14 In English please, what is a pointer?
A pointer is a data type. It is the address in the memory of where a certain chunk of data is stored. It is not the value of the data. If we want the pointer to be the address of where a double precision number is stored, we declare double *f_ptr, if we want it to point to an integer, int *i_ptr, and so forth. Pointer arithmetic must be done carefully, or the program using pointers may behave in unexpected ways.
15 When I ran my program, i got ``segmentation fault'', what does that mean?
It means that you misused either an array or a pointer, and attempted to access a memory location inappropriately. This is a pointer boo-boo. Typically, the most common error leading to such a message is that you tried to read the values pointed to by a pointer, but never initialized the pointer (you forgot to point it to some memory location). For example, to point a pointer f_ptr to the address of the variable x, we would need a line like fptr = &x; in the code before we tried to read the value stored in that location, via printf(``%f\n'', *fptr);. Remember to point your pointers before you try to read what they point to.
16 How can I pass a string to a function?
With considerable care. Strings are arrays of characters, or pointers to arrays of characters. The following code example solves this problem. Note the use of a global array to hold the string, and a pointer pointing to the first character.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char S[10];
int n;
char *stri;
int parsecommandstring( char *stri);
main(){
stri=&S[0];
do{
scanf("%s",stri); /* read in the string from the console */
n=parsecommandstring(stri); /* pass it to a function */
printf("%s=%d\n",S,n);
}while(1);
}
int parsecommandstring( char *stri){
if(strcmp(stri,"menu")==0)
return(109);
else return(110);
}
17 What is meant by a 16 or 32 bit compiler?
This refers to the size of floating point data. Thirty-two bit is more decimal places, higher precision, among other things. The Borland Turbo-C compiler is 16 bit, as are most DOS compilers. Microsoft PowerStation FORTRAN uses a 32 bit virtual extension to emulate 32 bit functionality. The gcc C compiler is 32 bit clean, and Java is actually 64 bit. That's a lot of decimal places.
18 I want to compute some stuff to 100 decimal places, any suggestions?
Use the GNU Multiple Precision library (gmp), which lets you keep as many decimal places as you have hard drive space. It is the fastest multiple precision library available, and uses Karatsuba and FFT multiplication schemes to work with very large numbers, which are stored as fullwords.
Here is a very simple example
#include <stdio.h>
#include <math.h>
#include <gmp.h>
main(){
mpf_t ONE,SEVENTEEN, ratio;
mpf_init2(ONE,2048);
mpf_init2(SEVENTEEN,2048); /* set precision to 2048 bit */
mpf_init2(ratio,2048);
mpf_set_ui(ONE,1);
mpf_set_ui(SEVENTEEN,17); /* initialize to unsigned integers */
mpf_div(ratio,ONE,SEVENTEEN); /* divide */
mpf_out_str(stdout,10,300,ratio); /* output 300 digits of 1/17 base 10 */
mpf_clear(ratio);
mpf_clear(ONE);
mpf_clear(SEVENTEEN);
}
Here is a FORTRAN95 high precision module. It is however very crude, using simple grade-school digit-by-digit multiplication with carry-over, and Newton's method for iterative inversion for division. It is what you would try if you were writing such a set of routines yourself with little or no knowledge of modern algorithms. And it does work.
19 How do I create or open a file for output or input?
By declaring a pointer to a FILE structure (this is archtecture specific), and by opening and closing the file. For example
FILE *f_ptr,*g_ptr;
f_ptr=fopen("indata","r"); /* open read only */
g_ptr=fopen("outdata","w"); /* open read/write*/
.
.
.
fclose(f_ptr);
fclose(g_ptr);
20 I need to create many files for output, and want the names to be numbered, how can it be done simply?
The following example shows how to create filesnames with some basename ``data'', followed by an integer label of no more than four characters. The label is generated in a loop, converted into a string and stored in a buffer. The buffer is concatenated onto the base name to create the full file name. This file is opened for writing, then closed, but nothing is written to it.
#include<stdio.h>
#include<stdlib.h>
int n;
FILE *fptr;
main(){
char *base_ptr="data";
char name[10], sbuff[8], *which;
for(n=0;n<4;n++){
strcpy(name,base_ptr);
which=gcvt((float)n,4,sbuff);
strncat(name,which,4);
printf("Creating file %s\n",name);
fptr=fopen(name,"w");
fclose(fptr);
}
}
You could use this method to create a data set, write it to a numbered file, create another and write it to another file, and so on.
You could use this method to create mpeg movies from a collection of
snapshots of an evolving system, if you have mpeg_encode. Here is an example program using the method above that draws snapshots of a quantum wavepacket hitting a potential barrier. It creates a mess of pnm files, all sequentially numbered. Use this script and this parameter file to automate the creation of mpegs.
21 I want my program to ask me which file I want to open, and then list all of the files in my working directory. How do I do it?
On a UNIX machine, you would use system(), which accepts a command string. Consider the example below.
#include<stdio.h>
#include<stdlib.h>
char S[10];
char *stri;
main(){
stri=&S[0];
printf("Should i list your C files?\n");
scanf("%s",stri);
if(strcmp(stri,"yes")==0){
system("ls -l *.c");
}
else
printf("have it your way then\n");
}
22 What are assertions, and can I override them if they are used in a program?
Assertions are a powerful feature of C that can be used to halt a program completely if some condition is not met. A nice example is the code below which will prevent the program from returning ``nan'' if we attempt to take the (real) square root of a negative number
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<assert.h>
float root (float x){
assert( x >= 0.0);
return(sqrt(x));
}
Execution will halt altogether if the assertion fails. Assertions are best used in debugging programs, and can be disabled in the final version of the program compiled from the code with a DNDEBUG macro definition;
gcc -o program -DNDEBUG program -lm
23 I tried to use a macro instead of a function to cut down overhead, and my program segfaults when I run it. What's wrong with it?
Macros can never be passed a pointer. Pointers should be worked on by functions instead of macros.
24 I am migrating to UNIX from the Borland Turbo-C compiler. Is there a UNIX version of the Borland conio console input-output library, and the Borland graphical interface?
Yes, there is a Linux conio library linux-conio , and bgi and grx libraries for root window animations. You can get these (libgrx-1.0.4.Elf.tgz, bgi_library.tar.gz) from
ftp://sunsite.unc.edu/pub/Linux/libs/graphics. They require the VGA library.
25 I have an executable program for which I would like to have the source code. Can it be ``decompiled''?
In a word, no. Some very simple binary files can be partially decompiled, but not unambiguously.
There is currently a project called bastard on freshmeat.net that can decompile to assembly. I am not sure how well it works. It is aptly named; most people want to decompile in order to pirate commercial software.
Java can be completely decompiled to pristine source; get the jad fast decompiler.
26 I want to use assembly language in an inline function, but when I look at samples of assembly for Linux it looks completely different than the examples in my MASM or TASM assembly books. What is going on?
Both MASM and TASM assemblers for x86 architecture use Intel assembly syntax. Linux uses the GNU assembler gas, which reads AT&T syntax, and the two are different. There is a simple solution; write your assembly in Intel syntax and convert it to AT&T syntax with the intel2gas translator.
Gcc will compile a C code into assembly with the -S switch. You can use this to generate simple examples of AT&T assembly. For instance the generic ``Hello'' C program can be compiled to assembly with
gcc -S -o hello.s hello.c
and can be linked and and assembled with as
as hello.s -o hello.o
gcc -o hello hello.o
A good Intel-syntax assembler is nasm , here is a local copy
27 When I try to compile a program using some dynamically linked library that I just installed, I get a linker error ``/usr/i686-pc-linux-gnu/bin/ld: cannot find -lgrx'', how can I fix this?
As root, run ldconfig -v, which will update the dll database. You could also locate the libgrx.so library; say it is in /usr/local/lib, then type
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib. If this does not work, chances are it is because there is no link from libgrx.so.n to libgrx.so, where n is the major revision number of the library. You can make this link (as root) by going into the library's directory and typing ln -s libgrx.so.n libgrx.so, and then rerunning ldconfig -v.
Note that for this to work, your /etc/ld.so.conf file must contain a line with the full path to where libgrx.so.n lives. Comprende?
28 When I try to compile a program, the compiler claims that some header or library cannot be found. Give me a simple fix.
Find the header, suppose it is in /usr/local/include, or the library, suppose it is in /usr/share/lib. Pass these to gcc via
gcc -I/usr/local/include -L/usr/share/lib -o prog prog.c -llibs
29 I wrote a really useful program and compiled it on DOS, but it won't run on my Linux box. What can I do?
Executables for different operating systems or machine architectures are incompatible. You should recompile your source on the other machine. If it is ANSI and POSIX compliant code, it will recompile. If not, you may need to rewrite it or try to run it in an emulator. Executor will let you run a virtual MacIntosh on top of Linux, dosemu will let you run a virtual DOS and wine a Win32 system on top of Linux.
If you are stuck with a Win32 machine, you could get the cygnus toolchain, which is a free and very powerful UNIX emulation layer and gcc compiler kit that runs on NT4 and Win95. This has become so popular that there are instructions for building cross-compilers so that Linux boxes can build programs to run in this emulator. Get it from http://www.cygnus.com.
You could cross compile; get a set of special headers and a version of gcc built on your computer to produce executables for other operating systems. This is rather difficult. There is a complete cross compiler for building 32-bit programs for OS/2 and DOS on a Linux system, available from
ftp://sunsite.unc.edu/pub/Linux/devel/msdos.
30 I wrote a simple program in C++, but a C compiler won't compile it. Why not?
C++ violates some C standards such as variable declaration and initialization. In C all variables really should be declared before any are initialized. A line like
for( int n=0;n<6;n++){
is allowed in C++ but not in C; you can't declare a variable within a loop. This particular requirement may be relaxed in gcc-3.
Comments in C must be correctly delimted; /* comment text */, and in C++ a double backslash before any text renders it into a comment.
I find that you simply have to be careful with the orders of variable declaration and initialization, and you will be fine.
31 I wrote a parallelized program using pthreads, but it is no faster than the non-parallel version, why not?
You get little or no advantage from parallelization unless you have a computer with more than one CPU. Why do you think I run duals and quads?
If you have two computers on an ethernet, you can distribute the computations in your program using pvm or mpi. Then your code will double in speed.
32 I think I might learn assembly language. Will that make my programs run faster?
Maybe, if you have a really poor C compiler. Modern optimizing C compilers produce executables that are as fast as hand coded assembly. You could further tweak your C by compiling to assembly and tightening up you code, especially loops, to make the executable small enough to fit into you computer's cache. Most really good programmers tell me that assembly is not worth the effort anymore that it once was, now that compiler technology is so good.
Some very tight loops in function code can be tweaked by compiling it to assembly and using the results as an inlined assembly function in a C program. A macro may actually be even faster. This is about the only use of assembly that I have gotten into.
33 I have a whole bunch of simple functions that I want to compile into a static library. How do I do it?
Step 1; compile each routine to an object file.
Step 2; archive the objects into a library.
Step 3; write a header file.
Step 4; use the library by linking with it.
gcc -c func1.c func2.c func3.c func4.c
ar -a libmine.a func2.o func3.o func4.o
ranlib libmine.a
gcc -L./ -I./ -o program program.c -lmine
34 I have a whole bunch of simple functions that I want to compile into a dynamically linked library (dll). How do I do it?
Step 1; compile each routine to an object file.
Step 2; link the objects into a library.
Step 3; write a header file.
Step 4; use the library by linking with it.
gcc -c func1.c func2.c func3.c func4.c
ld -o libmine.so -shared func2.o func3.o func4.o
gcc -L./ -I./ -o program program.c -lmine
There are other ways to do this, but I like this method.
35 I am sick of typing in those long compile lines, is there some way to automate compilations?
There are two ways. Simplest is to use a shell script to build your project. Here is an example;
#! /bin/bash
XLIBPATH="/usr/X11R6/lib"
LIBS="-lplot -lXaw -lXmu -lXt -lSM -lICE -lXext -lX11 -lm"
echo
echo " Locating required GNU libplot libraries"
if test -f /usr/lib/libplot.so
then
echo " libplot.so is in /usr/lib"
else
if test -f /usr/lib/local/libplot.so
then
echo " libplot.so is in /usr/local/lib"
else
echo " Cannot find libplot.so, quitting"
exit
fi
fi
gcc program.c -o program -L$XLIBPATH $LIBS
Once to save this as build.sh, type chmod a+x build.sh, and run ./build.sh to recompile your program.
The second method is more sophisticated; use make. This requires that you write a Makefile, which tells make how to build your project.
36 I used GOTO in BASIC and in FORTRAN77, but I never see it in C, how do I use GOTO in C?
The use of goto is regarded as poor programming in C, but as good programming in BASIC and FORTRAN77. There are many better means of interrupting flow and control than goto in C, such as switch/case/break, and even if/else or do/while are preferable. However goto is available in C. You must use a label, here is an example;
generate:{
m1=2.0*(float)rand()/max-1.0;
m2=2.0*(float)rand()/max-1.0;
b=sqrt(m1*m1+m2*m2);}
if(b>1.0) goto generate;
theta=2.0*atan2(R_cl,2.0*b);
det=floor(180.0*theta/PI);
printf("%d\n", det);
}
37 I want to read in a certain number of bytes of data of unknown type into a buffer from some file, fscanf() can't do it. What should I use?
You need to use file descriptors, a buffer, and a low-level input routine such as read. Here is a simple example;
char *tmp, Tmp[128]; /* buffer and pointer to it */
unsigned long i; /* the file descriptor */
tmp=&Tmp[0];
i = open("/proc/stat", O_RDONLY); /* associate descriptor with file */
read(i, &Tmp, sizeof(Tmp)); /* read 128 bits into buffer */
close(i); /* close file descriptor */
38 What is a structure, and how do I declare and initialize one?
Structures are heterogeneous data types composed of many sub-data called members. Consider a simple program that manipulates atomic structure data read in from an xyz file;
struct Atom {;
float position[3]; /* x and y and z coordinates of its position */
char *name; /* a one character name label, C,H,N,O,S... */
float vdist; /* distance from vantage point */
int clr[3]; /* color, RGB */
float scale; /* compute distance of atom to observer, a */
/* correctly sized ball illustrating perspective*/
} A[MAX],tempA;
we can then use the dot syntax to assign values to various members of an instantiation of the structure;
A[n].position[0]=tmpx;
A[n].position[1]=tmpy;
A[n].position[2]=tmpz;
We use the arrow operators to access members of pointers to structures;
void getAtomattribs( struct Atom *At){
int choice;
float rad, scaleindicator;
switch (choice=(int)(At->name)){
case 67:{At->clr[0]=0.0; /* Carbon */
At->clr[1]=65535;
At->clr[2]=0;
rad=1.0; break;}
case 72:{At->clr[0]=0; /* Hydrogen */
At->clr[1]=0;
At->clr[2]=65535;
rad=0.3; break;}
}
scaleindicator=dist(vantagex,vantagey,vantagez,0.0,0.0,0.0);
At->scale=sqrt(rad*(scaleindicator/At->vdist));
}
Structures are used in parallel programming with pthreads, and in almost all sophisticated programs involving complicated data. A FILE is in fact a special C-structure, as are directories, sockets, socket addresses, and so on. A pointer to a structure can be used to pass a gigantic amount of data to a thread as a single object.
39 What is a class in C++ or objective C?
A class is a structure with members that can be functions or operations. They are used in object-oriented programming to push code reuseability and inter-operability to the extreme.
40 Can C use complex numbers? How do I declare them?
In a word, yes. Precise syntax is compiler-dependent. On a Linux/gcc system, you would do the following;
__complex__ double z1,z2; /* declare */
__real__ z1=2.0;
__imag__ z1=3.0; /* initialize by real/imag parts */
z2=1.0+3.0i; /* initialize as a complex */
gcc treats these numbers like any other, and basic operations such as +, -, *, / are overloaded to correctly handle them. The real and imaginary parts are treated as ordinary doubles. Math library functions are not overloaded; you need to handle this yourself;
__complex__ double Cexp( __complex__ double z){
__complex__ double tmp;
__real__ tmp= exp(__real__ z)*cos(__imag__ z);
__imag__ tmp= exp(__real__ z)*sin(__imag__ z);
return(tmp);
}
As you can see this is no big deal.
41 I translated a matrix manipulation program from FORTRAN77 to C, and the FORTRAN77 version is a lot faster. How do I fix this?
FORTRAN77 reorders the array storage in the heap (available machine memory) so that columns rather than rows are stored contiguously (in adjacent memory sites). C does the opposite; rows are stored contiguously.
This means that a FORTRAN77 matrix program naively translated into C will generate cache misses as it loads the array members into memory. Switching the order of row/column loops will fix this.
I have obtained better than five to one speed increases this way. My C matrix routines with optimization on glibc-2.2 and gcc-2.95.2 are a little faster than my original FORTRAN77 routines when
compiled correctly. If you Strassenize the matrix storage and multiplication using pointers and unions (contiguously stored structures), you can make your matrix manipulation programs run many times
faster in C than in FORTRAN77. Then you can parallelize. Get the picture?
Cache misses can often be detected and eliminated with the use of a cache profiling library such as cacheprof , linked at runtime.
42 How do I find a particular OpenSource program?
Check all the usual suspects; appwatch, or go to
GNU headquarters. You could try tux
if it is Linux specific.
43 How do I install OpenSource software?
First you download and unpack it. If it ends in .tar.gz or .tgz, type
tar xvzf files.tar.gz
of course giving the name of the software package in place of the bogus name above. If it ends in .tar.bz2 use
bunzip2 files.tar.bz2
tar xvf files.tar
These commands will create a source directory which we will call files_dist. Go into this directory
and run the configure script, but first decide where you want the software installed, I suggest
/usr/local/bin. If that is your choice, type
./configure --prefix=/usr/local
make
Now wait until the compile (usually requiring make, gcc, autoconf, libtool and binutils
) has completed. Now log in as root and type
make install
ldconfig -v
and you are ready to use the new software.
44 I think my program has a memory leak, how can I find it and eliminate it?
Use memwatch , a memory leak detection and locator library.
45 I want my program to be able to produce a PDF graphic. Are there any free PDF graphics libraries?
Get ClibPDF , or the local copy . The library is simple to use, here is a Fourier series program that creates PDF files of Fourier sums. There may be a newer version available, check its documentation. This gives you source code. If you don't care about source, try pdflib, which is more modern and has good documentation.
46 I never bother to properly indent my code and it looks like hell. Oh what shall I do?
Never fear, indent is here. Get indent from here . Lots of other good things there as well.
47 Is there a basic interpreter for Xwindows with full xterm graphic support?
Yes. See X11-Basic , which is an ATARI-ST Gfa-Basic variant with full Xwindow graphics support. I doubt that it is ANSI-compliant, but who cares, if it works for you?
48 What about graphics support for FORTRAN, are there add-on libraries that offer graphics support?
Try PlPlot . This offers simple graphics for C, C++, Python, Tcl, and FORTRAN. It allows you to make simple xy-graphs, log/semilog, contour, mesh 3D plots, and charts. I don't know if it ihas animation or double buffering capacities. It is available for MAC, UNIX, Win32, VMS and AMIGA platforms.
PSplot from here is a PostScript graphics library for FORTRAN, and there is always the old and venerable pgplot from here . Other useful FORTRAN utilities can be gotten from ripley. You should also check the fortran market for other tools.
After some extensive testing of these libraries, I don't think any of them stack up against plotutils-2.X.
I also suggest getting the g2 graphics library, which is very simple and can be used from FORTRAN or C. I have cross-compiled a version that runs on Mumit Khan's MINGw32 port of gcc-2.95.2 for WIN32 platforms, here is a zip archive. Unpack it and put the headers in your include path, and libraries in the lib path. Sample Fourier analysis programs. here is a simple animation BASIC style that runs in an X11 window, no double buffering, and a Monte Carlo integration animation to compute pi. The cross-compiled library produces only PostScript graphics.
Check out the documentation for g2. It is the smallest, fastest and most complete graphics package that I have found yet that works on LINUX and WIN32, with cygwin or mingw32, with C or FORTRAN.
49 How do I use random numbers in a C program? If I want to use randoms in FORTRAN77, do I have to write my own generator?
In C the random number generator is a function in stdlib, and must be seeded. The kernel then stores its state, and so this function is probably not threadsafe. A simple example of its initialization and calling is
#include<stdlib.h>;
#define SEED 17531
main()
{
long num;
srand(SEED); /* initialize the sequence */
num=rand();
}
Old hands usually like to randomly initialize the function off of the clock time, or the process-ID of the program calling the routine. In C the routine that returns the PID of the program is getpid(). This is a function prototyped in unistd.h, and returns a pid_t UNIX type. For example
#include<sys/types>
#include<unistd.h>
#include<stdlib.h>
main()
{
long num;
srand((unsigned int)getpid()); /* initialize the sequence */
num=rand();
}
In FORTRAN check out fortran market for three FORTRAN random number generators.
I prefere to use discrepancy sequences, which tend to return ``random numbers'' with superior statistical properties to those returned by typical generators. This technique is best suited to programs that create very many randoms for Monte Carlo simulations. A well-written discrepancy sequence Monte Carlo integration routine will achieve much higher precision than a random number routine, in fewer Monte Carlo timesteps. It is also very much faster than the garden variety generators.
50 I really want to use the time/timer functions to initialize randoms and time processes. Gimme Gimme Gimme.
Time, date, usage functions belong to time.h, and this header prototypes functions that load data pertaining to times and dates (which are UNIX time_t types) into a special struct tm. For example
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int i;
time_t t1,t2.dt;
struct tm *tptr;
main(){
(void)time(&t1); /* or use t1=time((time_t *)0); */
tptr=gmtime(&t1);
/* now we have loaded up the time struct, we can access its members */
/* this example is using Grenwich date and time */
printf(``GM-date is %d/%d/%d\n'', 1900+tptr->tm_year, \
1+tptr->tm_mon,tptr->tm_mday);
/* and now the time */
printf(``GM-time is %d.%d.%d\n'', tptr->tm_hour,tptr->tm_min,tptr->tm_sec);
}
The time.h functions also can keep track of system time in seconds, micro and nano seconds for the purpose of timing processes. For these we use the interface to load up special structures rusage and timeval. For example the following block illustrates a timer that times processes in microseconds. The time interface is fairly rich in C, and you would be well advised to read through the relevent pages of the 499 programming guide. first.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/time.h>
#include<sys/resource.h>
#include<math.h>
int i;
float y;
static struct rusage ru_start, ru_end;
static struct timeval t_start, t_end;
double elapsed;
double difftime(struct timeval end, struct timeval start);
main(){
getrusage(RUSAGE_SELF, &ru_start); /* start timer */
/* now run some code to do computations you want to time */
getrusage(RUSAGE_SELF, &ru_end); /* stop the timer */
elapsed=difftime(ru_end.ru_utime,ru_start.ru_utime);
printf(``Elapsed time is %f\n'', elapsed);
}
double difftime(struct timeval end, struct timeval start){
double en, st;
en=((double)end.tv_sec+((double)end.tv_usec/1000000.0));
/* tv_usec is in microseconds, an integer, here we convert to seconds */
st=((double)start.tv_sec+((double)start.tv_usec/1000000.0));
return(en-st);
}
I can't tell you how this will work on a WIN32 platform, but it can be figured out by reading through your C compiler headers. That's how I figured this out for LINUX.
51 How does a class in C++ differ from C-structs?
A class is a struct with the added feature that struct members can be functions as well as data. The functions are called methods. At the most nominal level, neglecting all of the spiffy C++ features of inheritance and derivation, this is the fundamental difference. Subclasses also inherit properties and members from parent classes. Long before I learned that C had very good complex number capabilities, I wrote a simple C++ class for manipulating complex numbers. Here it is. download.
/* Cmplx.h header file for complex number class */
class Cmplx {
public:
double real;
double imag; // private members by default
public:
Cmplx(double InitR, double InitI); // a constructor for the class
Cmplx(){real=0.0;imag=0.0;} //default constructor, overloaded
Cmplx(double r){real=r;imag=0.0;}// real number constructor
Cmplx operator+(Cmplx); // four overloaded operators
Cmplx operator*(Cmplx); // for +,-,*,/
Cmplx operator-(Cmplx);
Cmplx operator/(Cmplx);
double Re(){return real;} // an inlined method
double Im(){return imag;}
double Modulus();
double Phase();
};
double Cmplx::Modulus()
{
return(sqrt(real*real+imag*imag));
}
double Cmplx::Phase()
{
return(atan2(imag,real));
}
Cmplx::Cmplx(double InitR, double InitI)
{
real=InitR;
imag=InitI;
}
Cmplx Cmplx::operator+(Cmplx z_add)
{
Cmplx temp(0,0);
temp.real=real+z_add.real;
temp.imag=imag+z_add.imag;
return temp;
}
Cmplx Cmplx::operator-(Cmplx z_add)
{
Cmplx temp(0,0);
temp.real=real-z_add.real;
temp.imag=imag-z_add.imag;
return temp;
}
Cmplx Cmplx::operator*(Cmplx z_add)
{
Cmplx temp(0,0);
temp.real=real*z_add.real-imag*z_add.imag;
temp.imag=imag*z_add.real+real*z_add.imag;
return temp;
}
Cmplx Cmplx::operator/(Cmplx z_add)
{
Cmplx temp(0,0);
double factor=z_add.Modulus();
double denom=factor*factor;
temp.real=(real*z_add.real+imag*z_add.imag)/denom;
temp.imag=(imag*z_add.real-real*z_add.imag)/denom;
return temp;
}
Cmplx Csin(Cmplx a)
{
Cmplx z(0,0);
z.real=sin(a.real)*cosh(a.imag);
z.imag=cos(a.real)*sinh(a.imag);
return z;
}
Cmplx Ccos(Cmplx a)
{
Cmplx z(0,0);
z.real=cos(a.real)*cosh(a.imag);
z.imag=-sin(a.real)*sinh(a.imag);
return z;
}
Cmplx Cexp(Cmplx a)
{
Cmplx z(0,0);
double factor =exp(a.real);
z.real=factor*cos(a.imag);
z.imag=factor*sin(a.imag);
return z;
}
Cmplx Clog(Cmplx a)
{
Cmplx z(0,0);
z.real=0.5*log(a.Modulus());
z.imag=atan2(a.imag, a.real);
return z;
}
// Here we overload the insertion operator to output Cmplx
ostream& operator<<(ostream& str, Cmplx& z)
{
str<<z.real<<"+"<<z.imag<<" i";
return str;
// notice that we return an ostream& object
}
To use this, you just include it in your C++ file, and follow the rules. For example consider the program below.
#include<iostream.h>
#include<math.h>
#include"Cmplx.h"
#define I Cmplx(0.0, 1.0) /* a definition of ``i'' */
Cmplx F (Cmplx k)
{
Cmplx temp;
temp = Cmplx (1.0, 0.0) / (Cmplx (10.0, 0.0) + k * I);
return (temp);
}
int main ()
{
blah blah blah
}
The Cmplx.h header shows tyou a nice example of operator overloading, see the overloading of cout in the last few lines.
52 What is operator and function overloading?
In C++ this applies to the retraining of a function or operator to handle new data types or classes. For example in C we use printf() with format strings which tell printf() what to print, floats, doubles, strings, and so forth. In C++ we use cout to print, but do not need to tell it what to print, we let the box figure it out. This is overloading. It is nice and convenient, but there is always a price; speed and control are sacrificed.
53 I wrote some nasty thang that left my machine littered with shared memory blocks and message queues, how can I clean it all up?
Learn to use shared memory and message queues properly for one thing, sloppy person. Try ipcs -q or icps -m to search for your IPC litter. Get its msgid or shmgid and remove it with ipcrm -msg msgig. The new Linux kernel has a new IPC interface, so you may need to read the kernel docs before you do this. Not a bad idea all the way around.
54 Java is too slow for my simulations, and my graphics flicker badly with my current C or FORTRAN graphics library. How can I double buffer them?
I only know how to do this in X using GNU libplot. Add the following line to set your plotter parameters
pl_parampl ("USE_DOUBLE_BUFFERING", "yes");
Another thing to try is to separate your computations to a thread, and build the graphics objects on another thread. This only helps on multiprocessors.
55 Why does pthread_create() only accept one stinkin datum as its operand? What good is that? Can't threads accept arrays of data?
The pthread functions should be passed a single datum, but that can be a pointer to a structure containing as much heterogeneous data as you wish.
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<pthread.h>
struct data{
float x[10000], newx[10000];
float shared, newshared;
int label;
} data1, data2, *dataptr1, *dataptr2;
void update(struct data *D); /* this is the action the threads take */
main(){
blah blah blah
pthread_t thread1, thread2; /* I am on a dual box */
...
dataptr1=&data1;
dataptr2=&data2; /* point them pointers or segfault! */
pthread_create(&thread1, NULL, (void *)update, (void *) dataptr1);
pthread_create(&thread2, NULL, (void *)update, (void *) dataptr2);
blah blah blah
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
...
}
56 My program uses libplot to create a graphic and write it to a file, but my program always segmentation faults near the end. Why?
You probably closed the output stream before you deleted the plotter handles, or else you did not delete the plotter handles. The end of your code should contain the following in this order
pl_closepl ();
pl_selectpl (0);
pl_deletepl (pl_handle);
fclose(fptr); /* close your output stream */
If this does not work, call me. I am just kidding, DO NOT CALL ME.
57 I need a very basic Java applet template. Please.
I assume that you will want to override most of the class methods, so...,
import java.awt.*;
import java.applet.Applet.*;
public class App1 extends Applet{
public variable declarations;
component declarations;
public void init(){
}
public void start(){
}
public void stop(){
}
public void destroy(){
}
public void paint(Graphics g){
}
}
58 What do I need to do to create and run Java applets in Netscape?
First you should write the code, store it in a file ending in file extension .java. Then compile it with
javac file.java
This creates file.class, the actual bytecode. Then write an HTML file of exactly the same name
<html>
<title>file applet</title>
<body>
You can put some text here, the web browser will display it but the appletviewer will not
<applet code="App1.class" Width=200 Height=200>
</applet>
</body>
</html>
Then run either
appletviewer file.html
or
netscape file.html
and you should be seeing your program running.
59 What do I need to do to create and run Java applications?
First you should write the code, store it in a file ending in file extension .java. Then compile it with
javac file.java
This creates file.class, the actual bytecode. Then if you have the Java VM or RTE on your machine and it is in your path, type
java file
and the application should run on the command line. The Linux JDK is available at Blackdown .
60 How do I pass command line parameters to my C program at runtime?
Through the argv[ ] keyword. This is the array of command line arguments. Remember that argv[0] is the name of the executable. Example
#include<stdlib.h> /* needed to use argc or argv[] */
main(int argc, char *argv[]){
which=atoi(argv[1]); /* retype argv[1] as an int */
why=atof(argv[2]); /* retype argv[2] as a float */
and so forth,...
}
61 How do I pass command line parameters to my Java application at runtime?
Through the args[ ] keyword. This too is an array of character command line arguments that must be recast into numbers if that is the appropriate action. As an Example
import java.awt.*;
import java.lang.Double;
class App1 {
public static void main (String args[]) {
String s=args[0];double angle;
angle = (double)Integer.parseInt(args[0]);
double alpha= Math.PI*angle/180.0;
double complete_K=Function.F(alpha);
System.out.println( angle +" "+complete_K);
}
}
class Function{
public static double F(double alpha) {
double[] a=new double[10];
double[] b=new double[10];
double[] c=new double[10];
a[0]=1.0;b[0]=Math.cos(alpha); c[0]=Math.sin(alpha);
for(int ct=1;ct<10;ct++) {
a[ct]=0.5*(a[ct-1]+b[ct-1]);
b[ct]=Math.sqrt(a[ct-1]*b[ct-1]);
c[ct]=0.5*(a[ct-1]-b[ct-1]);}
return(Math.PI/(2.0*a[9]));
}}
Note the class.member or class.method() syntax characteristic of object oriented languages.
To run this;
javac App1.java
java App1 45
62 I need an example of a simple Java applet illustrating layout and scrollbar use.
Here is a very simple example, a Fourier wave synthesizer that runs from Netscape and uses scrollbars to vary the Fourier coefficients.
63 I need an example of a simple Java applet illustrating mouse event handling.
Here is a very simple example, a Schrodinger equation integrator that runs from Netscape and solves the Schrodinger equation numerically for a few types of potentials in one dimension.
64 I need a WIN32 native compiler for C, C++ and FORTRAN77, but I am cheap and would rather profit from the hard work of others than part from any of my beautiful money. Oh what shall become of me?
Mumit Khan at UW-Madison has graciously given away his WIN32 ports of gcc-2.95.2. There is a link on the 499 site to this compiler. Get it, it is very well done. You could then redeem your slothful self by hacking out some cool and useful OpenSource code, compiling it with Mumit's compiler, and offering it to the world through the internet as a WIN32 port. This is how the Internet and its useful contributions such as the Linux kernel and gcc were developed in the first place. See, the Internet is much more than a global pornography redistribution system, it is a forum for the development and dissemination of knowledge. Or you could do nothing, hoard your money, and accept your fate.
65 I am reading in a data file, its length will vary, and I need to detect some end-of-file condition, how is that done?
With feof(), and a do-while loop, as in the following example
#include
#include
...
FILE *fptr;
main(int argc, char *argv[]){
if((fptr=fopen(argv[1],"r"))==NULL){
printf("No such file exists\n");
exit(1);}
n=0;
do {
fscanf(fptr, "%f", &data[n]);
n=n+1;
}while(!feof(fptr));
which stops the loop at the end of the file.
66 In BASIC I can make my simulation respond to keystrokes, but in C on UNIX the translated program simply halts on getch() and sits there waiting. Why, and how can I change this?
The behaviour of the terminal window on UNIX and DOS-based machines is very different. For example, on DOS-based machines, game programmers have a command kbhit() that detects a keyboard stroke, and TRUBASIC uses this extensively to generate interrupts that allow a user to interact with a running simulation. This is possible because the computer detects the keystroke but does not read it.
The UNIX behaviour of the keyboard is different. The default behaviour of the keyboard stroke is that it is read, and so a command such as getch() or scanf() will halt execution until the character is entered.
The behaviour of terminal input/output is controlled by the termios interface, which uses a special struct termios containing members that are behaviour and mode flags. Using these, we can override the defaults and make the terminal respond to a keystroke without reading it, and so emulate the DOS behaviour. This is advantageous if we absolutely must produce a simulation that responds the same way under UNIX that its DOS counterpart would.
Improper use of this routine may make your box unresponsive to the keyboard, so be careful
The following routine, gotten from Beginning Linux Programming by Neil Mathew and Richard Stones, will allow us to set up a terminal to read characters with canonical behaviour turned off. The keyboard will not echo characters, and will disable signals. There are two routines here, one to retrieve and store the default keyboard settings, and set the new ones, to be called at the beginning of a program, and one to restore these defaults. The defaults are stored in a termios struct.
#include
#include
#include
#include
#include
static struct termios initial_settings, new_settings;
void init_keyboard();
void close_keyboard();
void init_keyboard(){
tcgetattr(0, &initial_settings); /* grab default settings */
/* if you don't do this you are in deepest trouble */
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON; /* logical AND this flag */
new_settings.c_lflag &= ~ECHO; /* logical AND this flag */
new_settings.c_lflag &= ~ISIG; /* tilde means NEGATE */
new_settings.c_cc[VMIN] = 1; /* return after one character */
new_settings.c_cc[VTIME] = 0; /* instantly */
tcsetattr(0, TCSANOW,&new_settings); /* set up custom settings */
}
void close_keyboard(){
/* call this BEFORE your program terminates !!!! */
tcsetattr(0, TCSANOW,&initial_settings); /* restore defaults */
}
Here is the accompanying UNIX version of kbhit()
#include
#include
#include
#include
#include
static int pressed=-1;
int kbhit();
int readch();
int kbhit(){
char ch;
int nread;
if(pressed != -1)
return 1;
new_settings.c_cc[VMIN] = 0;
tcsetattr(0, TCSANOW,&new_settings);
nread=read(0,&ch,1);
new_settings.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW,&new_settings);
if(nread == 1){
pressed=ch;
return 1;
}
return 0;
}
int readch(){
char ch;
if(pressed != -1){
ch=pressed;
pressed = -1;
return ch;
}
read(0,&ch,1);
return ch;
}
Here is a nice simulation of planetary motion that uses these functions to control the behaviour of the simulation, all within a single thread. You need two files, PlotWindow.h and the program planet.c . This will behave just like the BASIC simulations, but of course the graphics in X will rock, and it will be like 100 times faster. Notice that the program stores the keyboard defaults, changes them, and then restores the defaults before termination. If you don't do this you WILL be sorry.
A simpler approach would be to run two threads in the program, one builds the graphics and displays it, another accepts keyboard commands, and the two use a block of shared memory, the listener write to it and the graphics thread reads it before each update.
67 I have legacy code written in ALGOL, is there an ALGOL to C translator?
Try marst , which does precisely what you want.
68 How do I compile a WIN32 executable on a LINUX machine?
With a cross-compiler. There are cross-compilers available from sunsite, and do a seach for cross-gcc or gcc-win on freshmeat. This last cross-compiler requires that the target WIN32 machine has the cygwin.dll library in the same directory as the execuutable. I have tested this, and it works well.
69 How do I create temporary files with unique names in the simplest way possible?
With tmpfile() and tmpnam(). here is a simple numerical integration of the Schrodinger equation by Runge Kutta that does this, and then runs system() calling graph -T X to plot the temp data file. It then removes it and lets you try another energy guess. Be careful with this one, it can get away from you.
Copyright Jeffrey R. Schmidt 2001. Who loves you?