Mathias Sven
Mathias Sven

Reputation: 431

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

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.

Upvotes: 3

Views: 63

Answers (1)

Mathias Sven
Mathias Sven

Reputation: 431

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.

Upvotes: 2

Related Questions