Pages

Tuesday, October 13, 2015

[OSX] OpenMP on OSX

If you are new to openMP and your operation system is OSX. You may encounter similar problems when compiling your first openMP code as I did.

Typically, the tutorial will ask you compile your source code with

g++ -fopenmp mycode.cpp

However, you may get confusing error messages like
ld: library not found for -lgomp
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I will not talk about the reasons in detail, all you/I have to know is that this is because on OSX our dear compiler g++ is  by default linked to clang (i.e. when you call g++ on OSX, we actually call clang), which is another compiler that has not support openMP yet. So the solution is: use another compiler supporting openMP.

Version 1: Download the clang-omp
It seems that this issue only happens on OSX, so a OSX-only solution is sufficient: use Homebrew to install another compiler named clang-omp.

brew install clang-omp
Then use this when compiling the code

clang-omp -fopenmp mycode.cpp


Version 2: Compile and isolate the latest gcc (still from Homebrew)
One alternative way is to compile and install another gcc from source code. In this way, we need to download the gcc source code and its dependencies by our own and compile and install them. That is, we are going to install gmp, mpc, mpfr before gcc, and we will put this compiler under a directory/prefix like the others (e.g. /usr/local/gcc5.0.2/)

However, I have encountered some issues so I switched back to Homebrew for installing them.
(you probably do not need to install the dependencies one by one, but I did not test this :p)

brew install gmp
brew install mpc
brew install mpfr
brew tap homebrew/versions
brew install gcc5 --enable-gcc

After the above steps, the gcc5 from Homebrew will be under something like /usr/local/Cellar/gcc5/5.2.0/bin
Next, we should modify our environment variable to easily call it

Let's say your shell file is ~/.bashrc (mine is ~/.zshrc though)
edit ~/.bashrc and add the statements like (your latest gcc might be different)

export GCC5_HOME='/usr/local/Cellar/gcc5/5.2.0' export PATH=$PATH:$GCC5_HOME/bin/ alias gcc5='g++-5'

Reload the shell (or reopen your terminal)
then we can use gcc5 to compile the openMP files and remain the gcc/clang untouched

gcc5 -fopenmp mycode.cpp


Reference:
https://solarianprogrammer.com/2015/05/01/compiling-gcc-5-mac-os-x/