Building the GNU Scientific Library on Windows
Including external and up-to-date C libraries for compilation under Windows can sometimes be a bit of a challenge, as they may be outdated or not available in binary form. For libraries under a free and/or open source license (e.g. GPL, MIT), there is at least the possibility to build them on your own computer.
For instance, while implementing a simple Metropolis-Hastings sampler in C (about which I will post soon), I needed reliable distribution and random-number functions. Of course I could have spent hours on Wikipedia and Stack Exchange to implement those functions on my own. But the goal was to learn about how to implement the MH algorithm in C, not everything else as well.
A quick web search led straight to the GNU Scientific Library (GSL), a library upon which many scientific software projects rely. Yet, in contrast to various Linux and Unix distributions, there was no easily downloadable and up-to-date GSL in binary form available for Windows.
Long story short, I needed to build the GSL on my own computer, preferably without having to first set up MSVC, Visual Studio, project files, et cetera. Preferring *nix build tools, I decided to rely on MSYS2 to compile the GSL.
The different steps required to build the GSL, and to link the library to your own code are discussed in the subsequent paragraphs.
Requirements
To build GSL on Windows, download
- GNU GSL source (see https://www.gnu.org/software/gsl/)
- MSYS2/MinGW-w64 toolchain (https://www.msys2.org/)
and install MSYS2.
Building
Copy the GSL source tarball gsl-x.x.tar.gz somewhere into your MSYS2 home directory, for instance into C:/msys64/home/username.
Open a MinGW terminal, navigate to the directory within your MSYS2 environment where you put the GSL tarball. Extract the source tar -xf gsl-x.x.tar.gz
. Change into the source directory, then ./configure --prefix=C:/Users/username/library_dir
. Compile the sources with make
, and wait until the library is built. Finally, make install
will install the different GSL library files into the directory you specified in the configure-step.
Linking
To compile a program using GSL functions, set the -lgsl
compiler flag to link to the GSL library.1 If the GSL is not located on a standard path (e.g. /usr/lib/* etc.) – which will most likely be the case when working on Windows – one may also need to specify where lib and include paths are to be found.
Assuming the GSL library files were installed into C:/Users/username/library_dir, and the program source is in myprogram.c, invoke the compiler with
gcc myprogram.c -LC:/Users/username/library_dir/lib -IC:/Users/username/library_dir/include -lgsl -lgslcblas -lm
or
gcc $(gsl-config --cflags) myprogram.c $(gsl-config --libs) -o myprogram
-
And possibly also
-lgslblas
if using GSL linear algebra subprograms, as well as-lm
for C’s math headers. ↩︎