Haskell call with C, getting a "multiple definition of the main" linker error

I am trying to learn the interface of Haskell and C. To start it, I wrote Inc.hs, the simplest thing I can imagine:

{-# LANGUAGE ForeignFunctionInterface #-}

module Inc where

import Foreign
import Foreign.C.Types

inc :: Int -> Int
inc = (+1)

foreign export ccall cinc :: CInt -> CInt
cinc :: CInt -> CInt
cinc = fromIntegral . inc . fromIntegral

And compiled it to create Inc_stub.h:

ghc -c Inc.hs

Worked great. Then I wrote a C file, also trying to be as simple as humanly possible:

#include <stdio.h>
#include "Inc_stub.h"

int main(int argc, char *argv[]) {
    int a = 1;
    hs_init(&argc, &argv);

    a = cinc(a);

    hs_exit();
    if (a == 2) {
        puts("Worked!");
    }

    return 0;
}

Tried to compile it, got this linker error:

ghc -no-hs-main inc.c Inc -o simplest
Linking simplest.exe ...
inc.o:inc.c:(.text+0x0): multiple definition of `main'
Inc.o:inc.c:(.text+0x0): first defined here
Inc.o:inc.c:(.text+0x31): undefined reference to `cinc'
c:/program files/haskell platform/7.10.2-a/mingw/bin/../lib/gcc/x86_64-w64-mingw32/4.6.3/../../../../x86_64-w64-mingw32/bin/ld.exe: Inc.o: bad reloc address 0x0 in section `.pdata'
collect2: ld returned 1 exit status

Everything was compiled using GHC 7.10.2 on the 64-bit version of Windows 10.

+4
source share
2 answers

I have done the following:

  • inc.c inc_main.c, C inc.o haskell
  • run ghc -c -no-hs-main Inc.hs -o Inc.o
  • C gcc -O -Wall -I/usr/lib/ghc/include -c inc_main.c
  • ghc -no-hs-main Inc.o inc_main.o -o simplest
+4

, , . @Hakala .

, Windows .

$ ghc -no-hs-main inc.c Inc -o simplest

GHC GCC inc.c inc.o. Windows inc.o, ghc -c Inc.hs. , ,

$ ghc -no-hs-main inc.c inc.o -o simplest

inc.o " ".

+4

Source: https://habr.com/ru/post/1624546/


All Articles