haskellprintfffi

Why does printf not work with ccall in haskell?


MRE:

{-# LANGUAGE ForeignFunctionInterface #-}

import GHC.Ptr
import Foreign
import Foreign.C
import Control.Monad

foreign import ccall unsafe "fibonacci.c fib" c_fib :: Int -> Int

example :: IO ()
example =
    print (c_fib 5)     

main = example

fibonacci.c

int fib(const int n) {
    if (n == 1) {
        printf("here");
        return 1;
    }
    else {
        return n*fib(n-1);
    }
}

result:

120 // does not print "here"

What is going on?


Solution

  • This happens because stdout is line buffered and printf("here") doesn't flush the buffer.

    You can flush it by printing a new line (printf("here\n")), or explicitly.

    printf("here");
    fflush(stdout);