GHC API equivalent of adding a C/C++ file/object to the compilation

52 views Asked by At

Say I have this GHC command:

ghc -ibuild/foreign/somelib \
  -lstdc++ \
  -outputdir "$buildDir" \
  foreign/somelib/somelib.o \
  src/Main.hs -o "$buildDir/Main"

The somewhat equivalent runGhc command is this, I think:

runGhc (Just libdir) $ do
  (setOutputFile (Just "build/Main") -> dflags) <- getSessionDynFlags

  setSessionDynFlags $ dflags
    { importPaths      = [".", "build/foreign/somelib"]
    , ldInputs         = [Option "-lstdc++"]
    , libraryPaths     = ["build/foreign/somelib"]
    , objectDir        = Just "build"
    , hiDir            = Just "build"
    }

  target <- guessTarget "src/Main.hs" Nothing Nothing

  setTargets [target]
  load LoadAllTargets
  return ()

However, that doesn't include the object file, and from looking at the documentation I am not sure how one would add it. Putting it as a target doesn't seem to work.

1

There are 1 answers

0
Mathias Sven On

As suggested in the comments, the solution is to pass it via the ldInputs:

  setSessionDynFlags $ dflags
    { importPaths      = [".", "build/foreign/somelib"]
    , ldInputs         = [Option "foreign/somelib/somelib.o", Option "-lstdc++"]
    , libraryPaths     = ["build/foreign/somelib"]
    , objectDir        = Just "build"
    , hiDir            = Just "build"
    }

Just like when working with ld, the order in which the ldInputs are defined matter.