C CODE GENERATOR TUTORIAL
Code generation from Mathematica involves converting programs written in the Mathematica language into other languages and then supporting them so that they can be executed. The Mathematica compiler provides a system for code generation into the C language.
This section describes some technologies that are related to code generation.
The Mathematica Compiler
The Mathematica compiler is an important way both to speed up and also to work with Mathematica computations. It does this by taking assumptions about the computations and rewriting them in more efficient ways.
A key way to use the Mathematica compiler is with the function Compile.
You can use the compiled function like any other Mathematica function, passing it real number input.
However, if you pass the compiled function an input that is not a real number, an error message is returned. Mathematica still returns a result, but has not used the compiler.
More detailed information can be found in the compiler documentation.
SymbolicC is a key part of Mathematica's C code generation system. It is used automatically, when Export or ExportString to C code is used. It provides a hierarchical view of C code as Mathematica expressions. This makes it well suited to creating, manipulating, and optimizing C code.
You can use SymbolicC for your own code-generation purposes. It is also used extensively for Mathematica's code generation tools.
To use SymbolicC, you first need to load the package.
Now you can start to build up elements of a C program. The following represents a variable declaration.
An important feature of SymbolicC expressions is that they are inert; they evaluate to themselves, staying in an unevaluated form.
Here is an assignment and an entire function.
You can keep the function as an expression, or you can convert it into a string that shows the C code.
More detailed information can be found in the SymbolicC documentation.
CCompilerDriver is a Mathematica package that gives an interface to C compilers installed on your computer. It can build shared libraries, executables, and object files. Since it is integrated with Mathematica, it is easy to use it for creating C code and linking this back in with Mathematica, for example, giving a convenient way to test the code.
Of course, you may choose to set up your own project or makefiles and not use the C Compiler Driver tools.
To use the package, it must first be loaded.
Now you can create a DLL from a file of C code.
This is a sample source file.
This creates a shared library, returning the full path.
If you do not have any suitable C compiler, the compilation will fail and a message will be generated.
The sample source file can work as a Wolfram Library and can be loaded with .
You can call the library function from Mathematica.
More detailed information can be found in the CCompilerDriver documentation.