Stack:编译独立源文件

Stack: Compile stand-alone source file

安装 Stack 后,您可以使用它为您安装 GHC。太棒了!

...现在如何用它编译文件?

明确一点:您应该 做的是编写一个包规范并让 Stack 构建它。但是肯定有一种方法可以在该项目中简单地编译一个小的帮助文件吗?构建一个完整的项目似乎很愚蠢,这样我就可以构建一个小的帮助程序并轻松地从 shell 中启用它 运行。

我知道我可以使用 Stack 运行 任何 Haskell 文件。但是我一辈子都想不出如何编译这个东西...

可以使用stack ghc -- <file names>编译和link一组文件(在Stack's user guide中有简要提及):

You'll sometimes want to just compile (or run) a single Haskell source file, instead of creating an entire Cabal package for it. You can use stack exec ghc or stack exec runghc for that. As simple helpers, we also provide the stack ghc and stack runghc commands, for these common cases.

--是为了确保我们传递的参数被发送到ghc,而不是被解析为stack exec的参数。这与尝试将参数传递给使用普通堆栈工具链创建的可执行文件时是一样的:stack exec myExe -foo-foo 传递给 exec,而不是 myExestack exec myExe -- -foo 表现符合预期。


例如:

Bar.hs

module Bar where

bar :: Int
bar = 5

Foo.hs

import Bar

main :: IO ()
main = print bar

编译(甚至不需要在构建文件中指定 Bar.hs,它会自动获取):

> stack ghc -- Foo.hs
[1 of 2] Compiling Bar              ( Bar.hs, Bar.o )
[2 of 2] Compiling Main             ( Foo.hs, Foo.o )
Linking Foo ...
> ./Foo
5

依赖关系也没有问题 - 看起来本地安装的所有包都可用于构建(您可以使用 containersQuickCheck 而无需任何额外的构建参数)。