Sz. Balázs
Sz. Balázs

Reputation: 13

How to manage ghci from C++?

I have a .hs file in which there is a Haskell function. My C++ program is supposed to run ghci, call the function, then write the output to a text file, then exit ghci. I thought it could be easily done with system(), with which I could have been able to menage the terminal, and do all these good things. But when I execute system("ghci"), the C++ program pauses and waits for me to be done with Haskelling.

How can I run a Haskell program from C++?

Upvotes: 1

Views: 96

Answers (2)

MathematicalOrchid
MathematicalOrchid

Reputation: 62848

Depending on what you're trying to do...

  • If you have a complete Haskell program, you can compile it using GHC and then run the resulting compiled program like any other program.

  • Alternatively, the runhaskell command takes the name of a source code file and runs it for you without needing to compile it first. (It still needs to contain a complete, runnable program though.)

  • If you have a source file containing several functions, you can use ghc Module.hs -e expression to run an arbitrary Haskell expression in the specified module.

  • Finally, you could try compiling the Haskell code into a dynamic library and link it into your C++ code... but that's really, really complicated.

  • It's also possible to call GHC as a library... but again, that's very complicated to do.

Upvotes: 5

Thomas Nelson
Thomas Nelson

Reputation: 683

ghci is the interactive repl. Use ghc to compile your .hs file to a binary executable. See the ghc docs. For example if you have myfile.hs with a main function then running ghc myfile.hs will create an executable myfile. Then in your c++ try system("./myfile").

Upvotes: 0

Related Questions