title: Dynamically loading compiled Haskell module - GHC 7.6
body: <p>I'm trying to dynamically compile and load Haskell modules using GHC API. I understand the API fluctuates quite a bit from on one version to another so I'm specifically talking about GHC 7.6.*.</p>
  
  <p>I have tried running the same code on MacOS and Linux. In both cases the Plugin module compiles fine but gives the following error on load: <code>Cannot add module Plugin to context: not interpreted</code></p>
  
  <p>The problem is similar to the one in <a href="https://stackoverflow.com/questions/12790341/haskell-ghc-dynamic-compliation-only-works-on-first-compile">this</a> where the module would only load if it was compiled in the same run of the host program.</p>
  
  <pre><code>-- Host.hs: compile with ghc-7.6.*
  -- $ ghc -package ghc -package ghc-paths Host.hs
  -- Needs Plugin.hs in the same directory.
  module Main where
  
  import GHC
  import GHC.Paths ( libdir )
  import DynFlags
  import Unsafe.Coerce
  
  main :: IO ()
  main =
      defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
        result &lt;- runGhc (Just libdir) $ do
          dflags &lt;- getSessionDynFlags
          setSessionDynFlags dflags
          target &lt;- guessTarget "Plugin.hs" Nothing
          setTargets [target]
          r &lt;- load LoadAllTargets
          case r of
            Failed    -&gt; error "Compilation failed"
            Succeeded -&gt; do
              setContext [IIModule (mkModuleName "Plugin")]
              result &lt;- compileExpr ("Plugin.getInt")
              let result' = unsafeCoerce result :: Int
              return result'
        print result
  </code></pre>
  
  <p>And the plugin:</p>
  
  <pre><code>-- Plugin.hs
  module Plugin where
  
  getInt :: Int
  getInt = 33
  </code></pre>