Introduction

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.

One mode of use is to create C code that conforms to a Wolfram Library; this can be compiled with a C compiler and linked back into Mathematica. This is how the CompilationTarget option of Compile works when it is set to "C"; it is described in more detail in the tutorial on CompilationTarget.

An alternative is to generate C code that can be used outside of Mathematica. Since this will execute outside of Mathematica, any external calls from the compiler cannot be supported. This means that high-level Mathematica functions such as Integrate or NDSolve that really do need Mathematica are not supported. On the other hand, if your code is based on the set of Mathematica that can be processed by the compiler, this can work outside of Mathematica. This is done by a runtime library that is provided to give support to the C code.

One way to use the code generator is to call Export and ExportString. The following creates a fragment of C code from a Mathematica function; this could be compiled into a shared library.

In[1]:=
Click for copyable input
Out[2]=

Export returns both the C file and the C header file. You can inspect the contents of the C file.

Looking at this code, there are a number of issues that need to be resolved in order to use it. This includes a library to provide implementations for functions such as the creation of the WolframLibraryData. These issues are discussed in other sections of this tutorial.

New to Mathematica? Find your learning path »
Have a question? Ask support »