可能重复:
Small Haskell program compiled with GHC into huge binary
最近我注意到Haskell可执行文件非常大。以下所有内容都是在Linux上使用GHC 7.4.1和-O2
编译的。
Hello World (
main = putStrLn "Hello World!"
) 超过了800 KiB。运行strip
能将文件大小缩减至500 KiB;即使在编译时添加了-dynamic
,它也没有太多帮助,最终的可执行文件会被削减至约400 KiB。编译一个非常原始的使用Parsec的示例,得到的文件大小是1.7 MiB。
-- File: test.hs
import qualified Text.ParserCombinators.Parsec as P
import Data.Either (either)
-- Parses a string of type "x y" to the tuple (x,y).
testParser :: P.Parser (Char, Char)
testParser = do
a <- P.anyChar
P.char ' '
b <- P.anyChar
return (a, b)
-- Parse, print result.
str = "1 2"
main = print $ either (error . show) id . P.parse testParser "" $ str
-- Output: ('1','2')
Parsec可能是一个较大的库,但我只使用它的一个小子集,实际上由上面生成的优化核心代码比可执行文件要小得多:
$ ghc -O2 -ddump-simpl -fforce-recomp test.hs | wc -c
49190 (bytes)
因此,我的最初假设是错误的,实际上程序中并没有大量的Parsec。
为什么可执行文件大小如此之大?有什么可以做的(除了动态链接)?
-split-objs
构建(请参见相关答案),否则它将不得不链接所有内容。 - hammarghc -O2 -dynamic test.hs && strip test && du -b test
=> 28712字节。 GHC版本为7.4.2,x86_64 Linux系统。 - David Unric