Linking to the LAPACK libraries from C++

What is LAPACK?

LAPACK is a collection of high-performance linear algebra routines written in FORTRAN and built on top of BLAS. LAPACK is usually provided as a shared library compiled either from the FORTRAN source or from C code automatically generated by the f2c conversion utility. The latter form is referred to as CLAPACK.

Calling conventions

In either case, the libraries obey FORTRAN calling conventions, so there are several things to keep in mind:

Example code

Here's a program that diagonalizes a real, symmetric N×N matrix arranged in the upper-triangular packed storage format.

#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#include <vecLib/clapack.h>
typedef __CLPK_doublereal doublereal;
typedef __CLPK_integer integer;
#else
typedef double doublereal;
typedef long int integer;
extern "C" void F77NAME(dspevd)
   (char*, char*, integer*, doublereal*, doublereal*,
    doublereal*, integer*, doublereal*, integer*,
    integer*, integer*, integer*);
#endif

integer eigensolve(vector<doublereal> &H, 
                   vector<doublereal> &Eval, 
                   vector<doublereal> &Evec)
{
   // Solve the eigenvalue problem with LAPACK's dsepvd routine

   integer N = Eval.size();
   assert(H.size() == N*(N+1)/2);
   assert(Evec.size() == N*N);

   integer info;
   char jobz='V';
   char uplo='U';
   vector<doublereal> work(1+6*N+N*N);
   integer lwork = work.size();
   vector<integer> iwork(3+5*N);
   integer liwork = iwork.size();

   F77NAME(dspevd)(&jobz,&uplo,&N,&(H[0]),&(Eval[0]),&(Evec[0]),&N,
           &(work[0]),&lwork,&(iwork[0]),&liwork,&info);

   return info;
}

Compiling and linking

On Mac OS X systems, the LAPACK libraries are provided as a part of the Accelerate framework. Linux requires that you link to /usr/lib/liblapack.so, /usr/lib/libblas.so, and /usr/lib/libg2c.so.

$ more makefile
CC=g++
CFLAGS=-O2 -ansi -pedantic

## for Mac OS X
LIBS=-framework Accelerate

## For Linux
#LIBS=-llapack -lblas -lg2c -lm

example: example.cpp
        $(CC) -o $@ $@.cpp $(CFLAGS) $(LIBS)

clean:
        rm example 2>&-