windowsocamlopam

"Error: Cannot find file '-lws2_32'" while compiling OCaml with OPAM on Windows


I'm following this tutorial to set up OCaml on windows. But the build process fails with this error:

[ERROR] The compilation of ocaml-base-compiler.5.2.1 failed at "make -j7".

#=== ERROR while compiling ocaml-base-compiler.5.2.1 ==========================#
# context     2.3.0 | win32/x86_64 |  | https://opam.ocaml.org#9f34991c038ca38ca54a43232b9cae1c14a3f1e3
# path        ~\AppData\Local\opam\default\.opam-switch\build\ocaml-base-compiler.5.2.1
# command     ~\AppData\Local\opam\.cygwin\root\bin\make.exe -j7
# exit-code   2
# env-file    ~\AppData\Local\Temp\opam-axele-22540\ocaml-base-compiler-22540-ab1bc1.env
# output-file ~\AppData\Local\Temp\opam-axele-22540\ocaml-base-compiler-22540-ab1bc1.out
### output ###
# cp flexdll-sources/flexdll_mingw64.o flexdll-sources/flexdll_initer_mingw64.o byte/bin
# [...]
# ** Fatal error: Cannot find file "-lws2_32"
# make[2]: *** [Makefile:1309: runtime/ocamlrun.exe] Error 2
# make[2]: *** Waiting for unfinished jobs....
# ** Fatal error: Cannot find file "-lws2_32"
# make[2]: *** [Makefile:1321: runtime/ocamlrund.exe] Error 2
# ** Fatal error: Cannot find file "-lws2_32"
# make[2]: *** [Makefile:1327: runtime/ocamlruni.exe] Error 2
# make[2]: Leaving directory '/cygdrive/c/Users/axele/AppData/Local/opam/default/.opam-switch/build/ocaml-base-compiler.5.2.1'
# make[1]: *** [Makefile:750: opt.opt] Error 2
# make[1]: Leaving directory '/cygdrive/c/Users/axele/AppData/Local/opam/default/.opam-switch/build/ocaml-base-compiler.5.2.1'
# make: *** [Makefile:831: world.opt] Error 2

I have tried installing with earlier version opam switch create ocaml-base-compiler 5.2.0 but this creates the same error.

Also tried removing the opam folder from ~\AppData\Local and rerun opam init -y

Edit - Solution

Posted as an answer


Solution

  • The issue was caused by an incorrect gcc version being prioritized in the PATH, leading to opam failing to compile OCaml. The problem was fixed by identifying the correct gcc installation (x86_64-w64-mingw32-gcc.exe) which was located in the Cygwin installation directory created by opam

    C:\Users\<username>\AppData\Local\opam\.cygwin\root\bin
    

    And then updating the environment path correspondingly. Finally, retrying

    opam switch create default ocaml-base-compiler.5.2.1
    

    with the correct gcc inplace, the ocaml switch was successfully created.

    Edit

    It seems the issue occurred because another gcc installation from Strawberry Perl was being prioritized in the PATH, overriding the gcc provided by opam.

    After removing

    C:\Strawberry\c\bin;
    C:\Strawberry\perl\site\bin;
    C:\Strawberry\perl\bin;
    

    and adding the cygwin-one to PATH it worked for me.