Data editing > Using subroutines in the edit > Writing your own routines > Writing subroutines in C
 
Writing subroutines in C
Quick reference
To write C subroutines, either type them into a file called private.c in the project directory, or insert them in the Quantum run immediately before or after the edit section as follows:
#c
C statements
#endc
More information
You can also include executable C statements in the edit section itself, as long as you enclose the code within #c and #endc statements.
Subroutines written in the C language must be filed in the file private.c in the current directory so that they will be compiled automatically with the rest of your Quantum program. If you have already compiled your subroutines before doing your Quantum run, the compiled version must be stored in the file private.o in the current directory.
Alternatively, you can insert complete C functions immediately before or after the edit section as long as you enclose the code between #c and #endc statements as shown here:
#c
/* C code
#endc
Here are some examples of how to include a function, square, that calculates the square root of a number. The Quantum edit that calls this function may look something like this:
real square 1f
ed
cx(181,190):4 = square(cx(1,3))
filedef srdata data
write srdata
end
When calling C functions, be sure to add the f option (where f stands for function) to the end of the declaration as shown above. If you omit this, Quantum will not recognize the function name and will issue a syntax error.
Note If the function you are calling does not return a value, or if you do not need to save the return value, you can use call to call the function and you do not need to declare it. For more information about call, see Calling up subroutines.
The first example is a C function in the private.c file:
#include <math.h>
double square(double dval)
{
return (sqrt(dval));
}
In the second example, the C code for the function has been included directly after the end statement in the Quantum run, and is enclosed by #c and #endc statements.
real square 1f
ed
.
end
#c
#include <math.h>
double square(double dval)
{
return (sqrt(dval));
}
#endc
It is also possible to include executable C statements directly into the Quantum edit section. Again, the code must be surrounded by #c and #endc statements. Here is an example that calls the standard C sqrt function directly and assigns the result to the Quantum variable x1.
ed
#c
#include <math.h>
x1 = sqrt(2.0);
#endc
cx(181,190):4 = x1
filedef srdata data
write srdata
end
In addition, any standard C library function, such as sqrt, can be declared and used directly in Quantum. So the above example can also be written as:
real sqrt 1f
ed
x1=2
cx(181,190):4 = sqrt(x1)
filedef srdata data
write srdata
end
For more information, see Calling functions from C libraries.
See also
Writing your own routines