Search code examples
c++macospathgsl

How to correctly set GSL path on mac


I have 'correctly' installed gsl on mac 10.13.2. In my c++ program, I am calling like usual, for example:

#include <gsl/gsl_math.h>

However while running the code, it can not find the gsl.

fatal error: 'gsl/gsl_math.h' file not found

I was wondering how to correctly link gsl PATH and libraries. I have tried,

  1. setting PATH and LD_LIBRARY_PATH in .bash_profile
  2. setting PKG_CONFIG_PATH to .../Gsl2.3/lib/pkgconfig

$which gsl-config returns

/Users/Softwares/HEP_Softwares/Install/Gsl2.3/bin/gsl-config

$pkg-config --libs gsl returns

-L/Users/Softwares/HEP_Softwares/Install/Gsl2.3/lib -lgsl -lgslcblas -lm

The only solution I can find is to run everytime with gsl linked. Like:

g++ $(gsl-config --cflags) mycode.cc $(gsl-config --libs) && ./a.out

But I was wondering if the GSL PATH can be set globally so that I can simply run

g++ mycode.cc && ./a.out

Solution

  • This is how c++ code is compiled and built:

    COMPILATION
    A compilation unit will take each cpp file and work its way through included headers to locate forward declaration of implementations of symbol signatures of used functionality in your code. In your case this involves gsl/gsl.h. If the file cannot be found in the search directories, which you can expand by specifying C_INCLUDE_PATH and or CPLUS_INCLUDE_PATH. If you omit #include <gsl/gsl_math.h>, your code will not compile as there are signatures, which cannot be found for GSL functions, which you use.

    LINKING
    Once you have compiled all cpp/cc files you need to link the binary, which can be executed. The linking process consists of a search through all symbols in your .o/.obj... files and a matching of the same to what it can find in your object files and the libraries, which you have specified using for example -lgsl. If all goes well, every lookup finds an according binary implementation for your machine's hardware model (i.e. 64bit/32bit ..., Arm, Intel, ... etc). If some are not found you will find linkage errors.

    What you are asking is, is there a way that C++ does not work as above? No!

    If you leave out #include <gsl/gsl.h> or if said file is not found in your search paths, compilation will not work or. If you omit -lgsl, linking will fail. If you find it annoying to write all the above stuff in the command line, write a Makefile to reduce the building process to ideally a simple command: make.

    Don't forget, that if you are linking against the shared library version of GSL, you might need specifying LD_LIBARAY_PATH on Linux and DYLD_LIBRARY_PATH on Macs as well.

    TLDR: you cannot ask a c++ compiler / linker to work differently as designed.