Generating C and Fortran Expressions

If you have special-purpose programs written in C or Fortran, you may want to take formulas you have generated in Mathematica and insert them into the source code of your programs. Mathematica allows you to convert mathematical expressions into C and Fortran expressions.

CForm[expr]write out expr so it can be used in a C program
FortranForm[expr]write out expr for Fortran
Export[file,expr,"C"]write out a C function that computes expr

Mathematica output for programming languages.

Here is an expression, written out in standard Mathematica form.
In[1]:=
Click for copyable input
Out[1]=
Here is the expression in Fortran form.
In[2]:=
Click for copyable input
Out[2]//FortranForm=
Here is the same expression in C form. Macros for objects like Power are defined in the C header file mdefs.h that comes with most versions of Mathematica.
In[3]:=
Click for copyable input
Out[3]//CForm=

If you want to generate a C version of an entire expression you can do this with Export to C.

Here an entire C function is computed from a Mathematica CompiledFunction expression.
In[4]:=
Click for copyable input
Out[4]=

One of the common motivations for converting Mathematica expressions into C or Fortran is to try to make them faster to evaluate numerically. But the single most important reason that C and Fortran can potentially be more efficient than Mathematica is that in these languages the user always specifies up front what type each variable will be—integer, real number, array, and so on.

The Mathematica function Compile makes such assumptions within Mathematica, and generates highly efficient internal code. This can be made to run even faster by setting the CompilationTarget to .

Compile[x,expr]compile an expression into efficient internal code
Compile[x,expr,CompilationTarget->"C"]compile into C code and link back into Mathematica

Compiling Mathematica expressions.

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