Search code examples
c++opencvmingwcross-compilingmingw-w64

Include external libraries when cross-compiling


I have a C++ project that uses OpenCV. It compiles and runs correctly on Mac but I would like to generate a Windows executable file from my Mac computer. I installed MinGW-W64 via Homebrew.

The doubt I have is the following. How do I tell MinGW-W64 to use the OpenCV libraries in order to cross-compile? As expected, just substituting g++ with x86_64-w64-mingw32-g++ does not work, outputting a host of errors related to OpenCV functions not being declared.

I have read that it is necessary to cross-compile the OpenCV libraries too, but I don't know what exactly this means. Is it that I need to create intermediate *.o files from my local OpenCV installation and linking them with my own C++ code's *.o files to finally generate a .exe output? And all of this using x86_64-w64-mingw32-g++?

If affirmative, I don't have much expertise with tools like Make or CMake but I guess there is a way to automate the whole process (my makefile is extremely simple, just generates the executable directly from source with one g++ command).

Could someone point me in the right direction regarding this? Thanks in advance!


Solution

  • Yes, you will need to cross-compile OpenCV with mingw in order to cross-compile your project for Windows. This means you will need to clone the source code and go though the build instructions using the mingw compiler. Once you've built OpenCV with mingw, you will need to point your project to use those libraries when you cross-compile.

    The OpenCV repository uses and contains cmake files to build the libraries. In general, cmake is used to generate makefiles, and then to build you run make with the generated makefiles. Since you want to cross compile, you will need to tell cmake to generate makefiles that works with mingw32-make instead of make (as ming32-make will use mingw g++ instead of normal g++). To have cmake generate mingw makefiles, you would call it with this -G "MinGW Makefiles" and then build withmingw32-make`. You may want to consider using static linking instead of dynamic linking, but if you want/need to use dynamic linking, you will need to copy the opencv build's output to a location on Windows and add that location to the PATH.

    Please keep in mind that enabling the CUDA support flag might not work when cross-compiling OpenCV with mingw. (I haven't checked recently but I think I remember that being a thing)