C ++ FFI Exception Capture Fails in Haskell

When using FFI in C ++ in Haskell, I can correctly catch exceptions when running a function in cabal repl , but when starting with cabal run exception does not get caught.

Below is a simple project that shows the problem:

exception.cabal

 name: exception version: 0.1.0.0 build-type: Simple cabal-version: >=1.10 executable exception main-is: Main.hs c-sources: main.cxx build-depends: base >=4.7 && <4.8 default-language: Haskell2010 extra-libraries: stdc++ 

main.cxx:

 # include <exception> # include <stdexcept> extern "C" int hs_exception() try { throw std::logic_error("THIS FAILS!"); } catch(...) { } 

and

Main.hs

 {-# LANGUAGE ForeignFunctionInterface #-} module Main where import Foreign.C.Types (CInt(..)) main = print c_hs_exception foreign import ccall unsafe "hs_exception" c_hs_exception :: CInt 

Work with REPL (ie GHCI) :

 cabal repl *Main> main 0 

But crashes when compiling with GHC and running :

 cabal run libc++abi.dylib: terminating with uncaught exception of type std::logic_error: THIS FAILS! [1] 12781 abort cabal run 

My compilers :

 ➜ gcc --version Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.3.0 Thread model: posix ➜ ghc --version The Glorious Glasgow Haskell Compilation System, version 7.8.3 
+7
c ++ haskell cabal
source share
1 answer

This value is for Mac, and was reported as GHC 11829 error . The fix is ​​to pass the -lto_library flag (LTO = link time optimization) to the Clang linker. This can be done with the executable section of the .cabal file as follows:

 executable myprog ... if os(darwin) ld-options: -lto_library 

Or the -optl-lto_library flag if you call ghc directly.

Note that it will be incorrect to recommend writing extra-libraries: to_library , which will not work.

+1
source share

All Articles