在默认的 Haskell Stack 项目中构建多个可执行文件

Joh*_*ler 5 haskell cabal haskell-stack hpack

我使用默认stack new设置来设置一个项目,该项目将一个服务器和一个客户端作为单独的可执行文件。我package.yaml以正确的方式更改了文件(截至 2020 年 4 月 21 日“没有用户指南”),并向我的app目录中添加了一个名为Client.hs.

我收到一条错误消息:“为非法列在‘其他模块’中的主模块‘Main’启用变通方法!”

我如何让堆栈构建客户端和服务器?

当我跑stack build我得到:

[... clip ...]
Building executable 'ObjectServer' for ObjectServer-0.1.0.1..
[4 of 4] Compiling Client
Linking .stack-work\dist\29cc6475\build\ObjectServer\ObjectServer.exe ...
Warning: Enabling workaround for Main module 'Main' listed in 'other-modules'
illegally!
Preprocessing executable 'Client' for ObjectServer-0.1.0.1..
Building executable 'Client' for ObjectServer-0.1.0.1..
[3 of 3] Compiling Client

<no location info>: error:
    output was redirected with -o, but no output will be generated
because there is no Main module.


--  While building package ObjectServer-0.1.0.1 using:
      D:\HaskellStack\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_3.0.1.0_ghc-8.8.3.exe --builddir=.stack-work\dist\29cc6475 build lib:ObjectServer exe:Client exe:ObjectServer --ghc-options " -fdiagnostics-color=always"
    Process exited with code: ExitFailure 1
Run Code Online (Sandbox Code Playgroud)

的相关部分package.yaml如下所示:

executables:
  ObjectServer:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - ObjectServer
  Client:
    main:                Client.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - ObjectServer
Run Code Online (Sandbox Code Playgroud)

K. *_*uhr 5

这里有两个问题。other-modules首先, in的默认值hpack是“source-dirs除了子句main中提到的模块之外的所有模块when”。如果查看生成的.cabal文件,您会发现由于此默认设置,每个可执行文件都错误地将另一个可执行文件的模块包含在其other-modules列表中。其次,该main设置给出包含主模块的源文件,但不会将 GHC 所需的模块名称更改为Main其他名称。因此,该模块仍然需要命名为module Main where ...,而不是module Client where...,除非您还单独添加了-main-is ClientGHC 选项。

所以,我建议修改Client.hs以使其成为Main模块:

-- in Client.hs
module Main where
...
Run Code Online (Sandbox Code Playgroud)

然后other-modules: []为两个可执行文件显式指定:

executables:
  ObjectServer:
    main:                Main.hs
    other-modules:       []
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - ObjectServer
  Client:
    main:                Client.hs
    other-modules:       []
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - ObjectServer
Run Code Online (Sandbox Code Playgroud)

这在我的测试中似乎有效。