This is documentation for Mathematica 6, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)

MathLink Development in C (Mac OS X)

This document describes how to compile and run MathLink programs written in the C language on Mac OS X systems. ("MathLink and External Program Communication" describes how to write MathLink programs in both the Mathematica language and the C language.)
This document does not teach you, in general, how to use your compiler and other development tools, nor does it teach you how to program in C. If you have any trouble building or running your MathLink programs, see the troubleshooting section at the end of this document.
Most of what is described in this document is Unix specific and is applicable to all supported Unix platforms. However, there may be some information which is specific to Mac OS X machines. To learn how to compile and run MathLink programs for another platform, see the Developer Guide for that platform.

Supported Development Platforms

The mathlink.framework shared library in the MathLink Developer Kit (MLDK) for Mac OS X can be used for Mac OS X 10.3.9 and newer and Xcode 1.1 and newer. The framework includes universal binary support for the 32-bit PPC, 32-bit x86, and 64-bit x86 architectures.

Installing the MathLink Components

The MathLink Developer Kit is located in the $InstallationDirectory/SystemFiles/Links/MathLink/DeveloperKit/MacOSX directory within your Mathematica directory.

Recommended Installation

CompilerAdditions Installation

The MathLink components that you will need to build MathLink programs have already been installed in the Mathematica bundle. One way to use these components is to leave them in the Mathematica.app directory and specify their full pathname when you call your compiler. This approach is taken in the example "makefiles" in the section "Building MathLink Programs".
An alternative is to copy these components ("mathlink.h", "libMLi3.a", and "mathlink.framework") into directories in which your compiler will automatically search for such files. These directories are commonly "/usr/include" or "/usr/lib" for the "libMLi3.a" and mathlink.h and /Library/Frameworks or ~/Library/Frameworks for "mathlink.framework". On many systems not all users have write access to these directories.

MathLinkExamples Installation

Copy the "MathLinkExamples" directory to your home directory.

MathLink Framework Components

The following is a description of each file or directory in the MLDK.

CompilerAdditions Directory

mathlink.h
mathlink.h is the header file that must be included in your C and C++ source files. It should be placed where your compiler can find it. You could copy this header file into the same directory as your source files, copy it into the same location as the standard header files, or leave it where it is if you added the MathLink directory to the search path for header files.
libMLi3.a
libMLi3.a is the static library that contains all of the MathLink functions. It should be included in your project. You could copy this library into the same directory as your source files or leave it where it is if you added the MathLink directory to the search path for libraries.
mathlink.framework
mathlink.framework is the dynamic library framework that contains all the MathLink functions. Use the framework when you want to build a version of your program that links dynamically with the MathLink library. You could copy this library in the same directory as your source files or leave it where it is if you added the MathLink directory to the framework search paths.
mprep
mprep is an application that writes MathLink programs automatically by processing "template" files. It may be convenient to copy this application into the same directory as your project or to create an alias to it.
mcc
mcc is a script that preprocesses and compiles your MathLink source files.
AlternativeLibraries/libMLi3.a
In $InstallationDirectory/SystemFiles/Links/MathLink/DeveloperKit/MacOSX/CompilerAdditions/AlternativeLibraries, the MathLink Developer Kit contains a version of "libMLi3.a" that was compiled on a Mac OS X 10.4.x system. The byte size of the C long double type changed between Mac OS X 10.3.9 and 10.4.0. If you are building on a 10.4.x system, use the "libMLi3.a" in the AlternativeLibraries directory. If you need a "mathlink.framework" that has been updated for 10.4.x, use the "mathlink.framework" found in $InstallationDirectory/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/CompilerAdditions. This "mathlink.framework" contains a Tiger-built Universal version of the MathLink framework suitable for running on Mac OS X 10.4.x for PPC, PPC64, x86-64, and I386 architectures.

MathLinkExamples Directory

This directory contains the source code for some very simple MathLink programs. By using this source code, you can learn how to build and run MathLink programs without having to write any code yourself.

PrebuiltExamples Directory

This directory contains prebuilt versions of the example programs. "Running MathLink Programs" describes how to run two of these programs. "Building MathLink Programs" describes how to build them yourself using the source code in the "MathLinkExamples" directory.

Building MathLink Programs

The general procedure for building MathLink programs is to include mathlink.h in any C or C++ source files that make MathLink function calls, to compile your source files, and then to link the resulting object code with the "libMLi3.a" library or "mathlink.framework" and any other standard libraries required by your application. If your application uses the MathLink template mechanism, then your template files must first be processed into a C source file using mprep.

Using MathLink Template Files

If your program uses the MathLink template mechanism as described in "MathLink and External Program Communication", you must simultaneously preprocess source files containing template entries using the mprep application. (A template entry is a sequence of lines that contain template keywords. Each entry defines a Mathematica function that when evaluated calls an associated C function.) When mprep processes such source files, it converts template entries into C functions, without changing other text, and writes out additional C functions that implement a remote procedure call mechanism using MathLink. The result is a C source file that is ready for compilation.
For example, the command
mprep addtwo.tm -o addtwotm.c
will produce a C source file "addtwotm.c" from the template entries and the other text remaining in "addtwo.tm". You would then compile the output file using the C compiler. If you use the "make" utility to build your program, you could add a rule similar to the following to your makefile.

Building MathLink Programs from the Command Line

What follows is a sample makefile needed to build the sample programs in the MLDK, including "addtwo" and "factor". To build a sample program, in this case "addtwo", evaluate the following command in the MathLinkExamples directory.

Using a Makefile

# This makefile can be used to build all or some of the sample
# programs. To build all of them, use the command
# 'make all'. To build one, say addtwo, use the command
# 'make addtwo'.

MLINKDIR = /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit
SYS = MacOSX
CADDSDIR = ${MLINKDIR}/${SYS}/CompilerAdditions

INCDIR = ${CADDSDIR}
LIBDIR = ${CADDSDIR}

MPREP = ${CADDSDIR}/mprep

all : addtwo bitops counter factor factor2 factor3 quotient reverse sumalist

addtwo : addtwotm.o addtwo.o
    ${CC} -I${INCDIR} addtwotm.o addtwo.o -L${LIBDIR} -lMLi3 -o $@

bitops : bitopstm.o bitops.o
    ${CC} -I${INCDIR} bitopstm.o bitops.o -L${LIBDIR} -lMLi3 -o $@

counter : countertm.o
    ${CC} -I${INCDIR} countertm.o -L${LIBDIR} -lMLi3 -o $@

factor : factor.o
    ${CC} -I${INCDIR} factor.o -L${LIBDIR} -lMLi3 -o $@

factor2 : factor2.o
    ${CC} -I${INCDIR} factor2.o -L${LIBDIR} -lMLi3 -o $@

factor3 : factor3.o
    ${CC} -I${INCDIR} factor3.o -L${LIBDIR} -lMLi3 -o $@

quotient : quotient.o
    ${CC} -I${INCDIR} quotient.o -L${LIBDIR} -lMLi3 -o $@

reverse : reversetm.o
    ${CC} -I${INCDIR} reversetm.o -L${LIBDIR} -lMLi3 -o $@

sumalist : sumalisttm.o sumalist.o
    ${CC} -I${INCDIR} sumalisttm.o sumalist.o -L${LIBDIR} -lMLi3 -o $@

.c.o :
    ${CC} -c -I${INCDIR} $<

addtwotm.c : addtwo.tm
    ${MPREP} $? -o $@

bitopstm.c : bitops.tm
    ${MPREP} $? -o $@

countertm.c : counter.tm
    ${MPREP} $? -o $@

reversetm.c : reverse.tm
    ${MPREP} $? -o $@

sumalisttm.c : sumalist.tm
    ${MPREP} $? -o $@

Building Mac OS X MathLink Programs with Xcode

Creating a Project

To create a project that can be used to edit, build, and debug "addtwo":
1.  Start Xcode.
2.  From the File menu, choose New Project.
3.  In the New Project dialog, select Standard Tool and then click Next.
4.  Create the Project.
5.  Copy the source files to the project directory.
6.  Run mprep on the template file.
Use mprep to generate a source file.
7.  Add files to the project.
  • In the addtwo project window under the Groups & Files pane click the triangle next to the addtwo entry.
  • Right-click on the Source entry.
  • Select Add ► Existing Files.
  • From the drop-down menu click <user name> directory and then click the addtwo directory, select addtwo.c, and click Add.
  • In the next drop-down menu be sure that the program addtwo box is checked in the Add To Targets section and click Add.
  • Right-click on the Source entry.
  • Select Add ► Existing Files.
  • From the drop-down menu click <user name> directory and then click the addtwo directory, select addtwo.tm.c, and click Add.
  • In the next drop-down menu be sure that the program addtwo box is checked in the Add To Targets section and click Add.
  • Click the Finder icon in the Dock to make the Finder active. Go to the folder where Mathematica is installed.
  • Click on the Mathematica icon while pressing the Ctrl key. A popup menu will appear. Select Show Package Contents to view the contents of Mathematica. Open the folders SystemFiles/Links/MathLink/DeveloperKit/MacOSX/CompilerAdditions.
  • Drag the file mathlink.h from the Finder window to the Source group to the Groups & Files list in Xcode. Make sure that Copy items into destination folder is not checked and click the Add button.
  • Drag the file libMLi3.a from the Finder window to the Source group to the Groups & Files list in Xcode. Make sure that Copy items into destination folder is not checked and click the Add button.
8.  Remove main.c from the project.
Right-click on the file main.c and select Delete. In the drop-down menu click the Delete References & Files button.
9.  Build the project.

Creating a Project for "factor"

To create a project that can be used to edit, build, and debug "factor":
1.  Start Xcode.
2.  From the File menu, choose New Project.
3.  In the New Project dialog box, select Standard Tool and then click Next.
4.  Create the Project.
5.  Copy the source files to the project directory.
6.  Change directory to the project directory.
7.  Add files to the project.
  • In the factor project window under the Groups & Files pane click the triangle next to the factor entry.
  • Right-click on the Source entry.
  • Select Add ► Existing Files.
  • From the drop-down menu click <user name> directory and then click the addtwo directory, select factor.c, and click Add.
  • Click the Finder icon in the Dock to make the Finder active. Go to the folder where Mathematica is installed.
  • Click the Mathematica icon while pressing the Ctrl key. A pop-up menu will appear. Select Show Package Contents to view the contents of Mathematica. Open the folders SystemFiles/Links/MathLink/DeveloperKit/MacOSX/CompilerAdditions.
  • Drag the file mathlink.h from the Finder window to the Source group to the Groups & Files list in Xcode. Make sure that Copy items into destination folder is not checked and click the Add button.
  • Drag the file libMLi3.a from the Finder window to the Source group to the Groups & Files list in Xcode. Make sure that Copy items into destination folder is not checked and click the Add button.
8.  Remove main.c from the project.
Right-click on the file main.c and select Delete. In the drop-down menu click the Delete References & Files button.
9.  Build the project.

Using mcc

mcc is a script that preprocesses and compiles your MathLink source files. It will preprocess MathLink templates in any file whose name ends with .tm, and then call "cc" on the resulting C source code. mcc will pass command-line options and other files directly to "cc". Following is a command that would build the "addtwo" application using mcc.
mcc addtwo.tm addtwo.c -o addtwo

Running MathLink Programs

The instructions in the "Building MathLink Programs" describe how to build two MathLink programs using source code in the "MathLinkExamples" directory. These two programs, "addtwo" and "factor", are already built for you in the "PrebuiltExamples" folder. Before building them on your own, you should try to run the prebuilt examples to verify that the MathLink system additions are installed and working and to learn what to expect from these examples when they are properly built. The rest of the comments assume that you are using the programs found in the Developer Kit.

Running a Prebuilt Example from the Mathematica Kernel

The first example program, "addtwo", is a MathLink template program that is installed into Mathematica. That is, this program runs in the background, providing, as a service to Mathematica, one or more externally compiled functions. To the Mathematica user, these functions appear to be built-in. In order to get this new functionality, the user of Mathematica must run the Install[] function. The "addtwo" program uses a template file that defines the Mathematica function AddTwo[] as a call to the C function addtwo(). (The template mechanism is described in "MathLink and External Program Communication".) The source code for this program looks likes this.
Evaluate the following two cells.
Click for copyable input
Click for copyable input
To see a list of the newly available functions, evaluate the following cell.
Click for copyable input
This displays the usage message for the AddTwo[] function as defined in the file "addtwo.tm".
Click for copyable input
Now try it:
Click for copyable input
See what happens if the sum of the two machine integers will not fit in a machine integer or if either argument is not a machine integer. (2^31-1 is the largest machine integer. If your compiler uses 2-byte integers, then 2^15-1 is the largest C int.)
Click for copyable input
The "addtwo" program is not prepared for big integers.
Click for copyable input
This does not match AddTwo[_Integer, _Integer].
Click for copyable input
Install[] called LinkOpen[] and then exchanged information with the external program to set up the definition for AddTwo[]. You really do not have to worry about these details, but if you are curious, evaluate the following.
Click for copyable input
When you are finished using the external program, evaluate the following.
Click for copyable input

Invoking the Mathematica Kernel from Within a Prebuilt Example

The second example program, "factor", is a Mathematica front end in the sense that the Mathematica kernel runs in the background providing, as a service to "factor", the computational services of the kernel—in this case, the ability to factor an integer typed by the user. These examples assume that Mathematica is installed in the Applications directory.
Launch the "factor" application by executing the following command.
After a moment, a prompt will appear requesting that you type an integer. Type an integer with fewer than 10 digits and press the Return key. (The other factor examples relax the restriction on the size of integer you may type in.)
The prime factors returned by Mathematica are printed, and "factor" closes its link with Mathematica.

Supported Link Protocols

The C function MLOpenArgcArgv() and the Mathematica function LinkOpen[] are documented in "MathLink and External Program Communication". On Macintosh OS X machines, the legal values for the LinkProtocol option are "TCPIP", "TCP", "SharedMemory", and "Pipes". A LinkProtocol is the mechanism used to transport data from one end of a connection to the other. "Pipes" is the default protocol for LinkMode->Launch links. "SharedMemory" is the default for LinkMode->Listen and LinkMode->Connect links.
Note that link names are unsigned 16-bit integers for the "TCPIP" and "TCP" protocols. Even though "TCPIP" link names are integers, they are still given as strings (of digits) to MLOpenArgcArgv() and LinkOpen[].

Troubleshooting

  • Turn off compiler optimization until your program is working. This makes compiling faster, debugging easier, and, besides, the optimizer may be broken and the cause of some problems. (Optimized code uses the stack and registers differently than unoptimized code in such a way that may expose or mask a bug in your code. For example, the common mistake of returning a pointer to a local variable may or may not cause a problem depending on stack and register use.)
  • Check the return values from the MathLink library functions or call MLError() at key points in your program. MathLink will often be able to tell you what has gone wrong.
  • The files "mathlink.h" and "libMLi3.a" are a matched set. If you have used an earlier release of MathLink, you should take care that you do not mix components when building your application.
  • Check whether the C compiler you are using supports prototypes. If it does not, you will need to change your code and the way you build your project. This is explained in the section "Building MathLink Programs".