Linker order error with matlab dynamic libraries and gcc on mac os x

Alec Jacobson

November 03, 2014

weblog/

I had a nasty time tracking down a runtime error in our libigl tutorials. It seems that the newest version of matlab comes with some dynamic libraries which do not agree with the stdc++ library of my gcc compiler. I had a link command that looked something like this:

/opt/local/bin/g++ -std=c++11
  /Applications/MATLAB_R2014b.app/bin/maci64/libmex.dylib \
  /Applications/MATLAB_R2014b.app/bin/maci64/libmx.dylib \
  ...

Here's the debugger output of the error I got at runtime

* thread #1: tid = 0x153aa3, 0x00007fff86d08866 libsystem_kernel.dylib`__pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x00007fff86d08866 libsystem_kernel.dylib`__pthread_kill + 10
    frame #1: 0x00007fff8341f35c libsystem_pthread.dylib`pthread_kill + 92
    frame #2: 0x00007fff8571fb1a libsystem_c.dylib`abort + 125
    frame #3: 0x00007fff8b1c007f libsystem_malloc.dylib`free + 411
    frame #4: 0x00000001001d47a0 libmex.dylib`std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >::~basic_stringbuf() + 96
    frame #5: 0x0000000100451da2 libstdc++.6.dylib`std::basic_ostringstream<char, std::char_traits<char>, std::allocator<char> >::~basic_ostringstream() + 36

Seems like libmex and libmx were the culprits. I fixed this problem by telling the linker to find the stdc++ library before the matlab dynamic libraries:

/opt/local/bin/g++ -std=c++11
  -lstdc++ \
  /Applications/MATLAB_R2014b.app/bin/maci64/libmex.dylib \
  /Applications/MATLAB_R2014b.app/bin/maci64/libmx.dylib \
  ...