Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading