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 the Wolfram Language and insert them into the source code of your programs. The Wolfram Language allows you to convert mathematical expressions into C and Fortran expressions.

Wolfram Language output for programming languages.

Here is an expression, written out in standard Wolfram Language form:

Expand[(1+x+y)^2]

Here is the expression in Fortran form:

FortranForm[%]

Here is the same expression in C form. Macros for objects like (RefLink[Power, paclet:ref/Power]) are defined in the C header file mdefs.h that comes with most versions of the Wolfram Language:

CForm[%]

If you want to generate a C version of an entire expression you can do this with (RefLink[Export, paclet:ref/Export]) to C.

Here an entire C function is computed from a Wolfram Language (RefLink[CompiledFunction, paclet:ref/CompiledFunction]) expression:

Export["squared.c", Compile[{x},x^2]]

One of the common motivations for converting Wolfram Language 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 the Wolfram Language 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 Wolfram Language function (RefLink[Compile, paclet:ref/Compile]) makes such assumptions within the Wolfram Language, and generates highly efficient internal code. This can be made to run even faster by setting the (RefLink[CompilationTarget, paclet:ref/CompilationTarget]) to "C".

Compiling Wolfram Language expressions.