gpt4 book ai didi

haskell - 如何使用库+可执行文件创建一个仍然使用 runhaskell/ghci 运行的 Haskell cabal 项目?

转载 作者:行者123 更新时间:2023-12-03 05:54:15 25 4
gpt4 key购买 nike

如果您declare a library + executable sections in a cabal file while avoiding double compilation of the library通过将库放入 hs-source-dirs 目录中,您通常无法再使用 ghcirunhaskell 运行项目,特别是如果可执行文件本身有辅助模块。

推荐的项目布局是什么

  • 只构建一次所需的内容
  • 允许使用runhaskell
  • 有一个干净的结构,没有黑客攻击?

最佳答案

假设您有一个 mylib 库、mylib-commandlinemylib-server 可执行文件。

您对库和每个可执行文件使用hs-source-dirs,以便每个可执行文件都有自己的项目根目录,从而避免双重编译:

mylib/                      # Project root
mylib.cabal
src/ # Root for the library
tests/
mylib-commandline/ # Root for the command line utility + helper modules
mylib-server/ # Root for the web service + helper modules

完整目录布局:

mylib/                      # Project root
mylib.cabal
src/ # Root for the library
Web/
Mylib.hs # Main library module
Mylib/
ModuleA # Mylib.ModuleA
ModuleB # Mylib.ModuleB
tests/
...
mylib-commandline/ # Root for the command line utility
Main.hs # "module Main where" stub with "main = Web.Mylib.Commandline.Main.main"
Web/
Mylib/
Commandline/
Main.hs # CLI entry point
Arguments.hs # Programm command line arguments parser
mylib-server/ # Root for the web service
Server.hs # "module Main where" stub with "main = Web.Mylib.Server.Main.main"
Web/
Mylib/
Server/
Main.hs # Server entry point
Arguments.hs # Server command line arguments parser

类似 stub 入口点文件mylib-commandline/Main.hs如下所示:

module Main where

import qualified Web.Mylib.Server.Main as MylibServer

main :: IO ()
main = MylibServer.main

您需要它们,因为可执行文件必须在名为Main的模块上启动。

你的mylib.cabal看起来像这样:

library
hs-source-dirs: src
exposed-modules:
Web.Mylib
Web.Mylib.ModuleA
Web.Mylib.ModuleB
build-depends:
base >= 4 && <= 5
, [other dependencies of the library]

executable mylib-commandline
hs-source-dirs: mylib-commandline
main-is: Main.hs
other-modules:
Web.Mylib.Commandline.Main
Web.Mylib.Commandline.Arguments
build-depends:
base >= 4 && <= 5
, mylib
, [other depencencies for the CLI]

executable mylib-server
hs-source-dirs: mylib-server
main-is: Server.hs
other-modules:
Web.Mylib.Server.Main
build-depends:
base >= 4 && <= 5
, mylib
, warp >= X.X
, [other dependencies for the server]

cabal build 将构建库和两个可执行文件,而无需对库进行双重编译,因为每个文件都位于自己的 hs-source-dirs 中,并且可执行文件依赖于图书馆。

您仍然可以使用 runghc 从项目根运行可执行文件,使用 -i 开关来告诉它应在哪里查找模块(使用 : 作为分隔符):

runhaskell -isrc:mylib-commandline mylib-commandline/Main.hs

runhaskell -isrc:mylib-server mylib-server/Server.hs

这样,您就可以拥有干净的布局、带有帮助程序模块的可执行文件,并且一切仍然可以与 runhaskell/runghcghci 一起使用。为了避免重复输入此标志,您可以添加类似的内容

:set -isrc:mylib-commandline:mylib-server

到您的.ghci 文件。

<小时/>

请注意,有时应该将代码拆分为单独的包,例如mylibmylib-commandlinemylib-server

关于haskell - 如何使用库+可执行文件创建一个仍然使用 runhaskell/ghci 运行的 Haskell cabal 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12305970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com