- Cygwin или MinGW? Собираем программы для Windows без Windows
- Содержание статьи
- GNU и Windows
- Cygwin
- MinGW и MSYS
- Ставим MinGW
- Hello World
- Продолжение доступно только участникам
- Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте
- MinGW32 make command on windows
- 2 Answers 2
- OpenCV C++ installation on Windows with MinGW
- Prerequisites
- Step 1
- Step 2
- Step 3
- Step 4
- Step 5
- How to compile makefile using MinGW?
- 6 Answers 6
Cygwin или MinGW? Собираем программы для Windows без Windows
Содержание статьи
В общем-то, даже в Microsoft уже признали проблему и сделали WSL (Windows Subsystem for Linux), чтобы запускать те приложения, у которых нативных версий под Windows нет. Однако если ты хочешь сделать свою программу доступной для широкой аудитории, то WSL вовсе не панацея, поскольку у среднего пользователя эта система вряд ли установлена и у нативных приложений возможностей для интеграции с Windows все равно больше.
Во многих случаях камень преткновения — не сам код программы, а система сборки. Если ты используешь кросс-платформенные библиотеки и не вызываешь специфичные функции POSIX, портирование может вообще не требоваться. Главное — собрать исполняемые файлы.
Сборка-то обычно и зависит от окружения POSIX. Если ты используешь GNU autotools, то скрипт ./configure у тебя на Bourne shell. CMake и ряд других систем сборки умеют генерировать скрипты под целевую ОС, но остается последняя «маленькая» проблема — нужна проприетарная и не бесплатная ОС. Есть вариант переложить задачу ее развертывания и лицензирования на кого-то другого и обратиться к сервису вроде Appveyor. Но можно вместо этого воспользоваться способностью GCC к кросс-компиляции и собирать программы на хосте с Linux (или macOS).
GNU и Windows
Для сборки программ с помощью GNU toolchain на Windows часто используют два проекта: Cygwin и MinGW + MSYS. У них схожие цели, но разные детали реализации. Давай разбираться.
Cygwin
Cygwin — самая полная реализация окружения GNU для Windows. Он предоставляет большую часть POSIX API в виде библиотеки, что позволяет собирать программы из UNIX без портирования, если только им не требуется семантика UNIX. Яркий пример — демоны, им нужен fork() и сигналы, которых нет в Windows, да и службы Windows устроены совсем иначе.
Кроме библиотеки, дистрибутив содержит набор классических команд UNIX и терминал. Реализации команд используют эту библиотеку и поддерживают некоторые возможности UNIX, такие как регистрозависимые имена файлов.
Целевой способ использования: если нет желания или возможности портировать программу на Windows или использовать только платформенно независимые API, ее можно собрать «под Cygwin», ценой зависимости от cygwin1.dll и относительной изоляции от всей остальной системы.
Многие люди ставили и продолжают ставить окружение Cygwin, чтобы иметь возможность использовать классические команды UNIX на Windows. Некоторые разработчики также включают Cygwin в инструкции для сборки своих программ под Windows, хотя сама программа не связывается с cygwin1.dll . Для этой цели может быть более правильно использовать MSYS.
MinGW и MSYS
Если цель Cygwin — сделать возможной сборку немодифицированных приложений на Windows ценой внешней зависимости, то цель MinGW + MSYS — производить приложения без внешних зависимостей.
MinGW и MSYS — это независимые пакеты, но их часто путают и смешивают друг с другом (а часто путают и с Cygwin). Можно сказать, что MinGW — это эквивалент GCC и binutils, а MSYS — расширенный эквивалент coreutils.
Начнем с MSYS. MSYS — это более «нативная» и легковесная альтернатива Cygwin. Этот пакет включает библиотеку с реализациями функций POSIX, но она предназначена для внутреннего пользования, и авторы категорически не рекомендуют связывать с ней свои приложения.
Библиотека MSYS не реализует UNIX поверх Windows, а следует соглашениям Windows — к примеру, сознательно не учитывает регистр букв в путях к файлам. Главная цель MSYS — предоставить нужные для скриптов сборки программы вроде Bourne shell, make и прочее, что обычно требуется для autotools.
MinGW содержит версии GCC и binutils (ассемблер as, компоновщик ld и так далее), которые производят исполняемые файлы для Windows в формате PE/COFF. Здесь мы и подходим к ключевому моменту: MinGW, как и все остальные части GNU toolchain, такой же платформенно независимый проект.
Кросс-компиляция в GNU toolchain уже давно обычное дело, и в GCC целевая платформа и хост независимы друг от друга. Можно запускать GCC на Linux для x86 и собирать программы для Linux на ARM, или наоборот. Совпадать не обязаны не только рабочая и целевая архитектуры процессора. Точно так же не обязаны совпадать даже ОС и формат исполняемого файла.
Ставим MinGW
Авторы многих дистрибутивов GNU/Linux уже постарались за нас, так что многие кросс-версии GCC, включая MinGW, можно поставить из репозиториев.
Например, в Fedora:
Если ты используешь macOS, то MinGW можно поставить из Homebrew: brew install mingw-w64 .
MinGW-w64, несмотря на название, поддерживает и Win32, и Win64. Это форк MinGW, который создали в первую очередь для реализации недостающей в оригинальном проекте поддержки Win64, отсюда и название.
В Fedora также присутствует ряд готовых кросс-версий популярных библиотек, например mingw32-qt .
Hello World
Для демонстрации соберем традиционный hello world. У кросс-версий GCC всегда есть префикс, для MinGW используются префиксы i686-w64-mingw32 и x86_64-w64-mingw32 .
Тестирование кросс-компилированных программ для других архитектур — непростая задача, но, поскольку наша целевая платформа — Windows на x86, мы легко можем протестировать их в Wine:
Продолжение доступно только участникам
Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте
Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», позволит скачивать выпуски в PDF, отключит рекламу на сайте и увеличит личную накопительную скидку! Подробнее
MinGW32 make command on windows
I am trying to install a simulation software on windows using MingW32 and cmake.
The problem I have is after I use :
From a Microsoft visual studio, (Otherwise I ran in other issue).
I then start a MinGW console and go to the repertory where my Makefile was created, and enter the command make, and here is what I get :
And naturally the make command does not actually execute. Why do I get the windows version ? No idea.
Interestingly enough, the name of the MniGW32 console change to add make at the end if I enter it more than once, and keeps on doing it later.
make —version gives the normal output, so I do not understand where the problem comes from.
2 Answers 2
If you use cmake . -G «MinGW Makefiles» you will need to call mingw32-make .
And just a hint: I assume you were previously building with Cygwin and for MinGW32 it should be -DCMAKE_INSTALL_PREFIX=»/c/Gromacs467″ instead of -DCMAKE_INSTALL_PREFIX=»/cygdrive/c/Gromacs467″
References
Instead of calling make directly, you can let CMake invoke the build for you with the following syntax:
The —target and —config arguments are optional and must point to your CMake project’s build directory. The main advantage to invoking your build this way is that CMake has already determined the build tool and knows where to find it and how to invoke it correctly. Invoking your build via CMake in this manner is likely to be more robust.
Basic CMake documentation for the —build option available here and some related material can be found in this blog post, particularly the section «Abstracting away the build tool» (disclosure: I wrote the blog article).
OpenCV C++ installation on Windows with MinGW
These days getting OpenCV running inside python is quite easy given conda does handle the installing the binaries and bringing the opencv python bindings inside python path.
However getting the same to run in C++ , is a different story. C++ is all about bringing in the right interface (hpp/header files) and binaries (so/dll) in the context of the program being compiled by the “g++” compiler. I will show you how I was able to set my system up for the same. Most tutorials out there will consider using an IDE like Eclipse or Netbeans. For bringing in “g++” (GNU C++ compiler) , we will use MinGW64. Remember we must use the 64bit variant since Mingw32 does not supports posix threads properly in windows. The ming64 binaries are built with a posix implementation that gives native posix but when compiled on windows will be slower compared to something built on windows native API (win32)
Prerequisites
- Windows (10/8/7) system
- Mingw-w64 , you can download from here
- OpenCv 3+ , official github repo
- Cmake , download from here
- Editor and terminal, do not care what you use. You can use notepad 😥 if you wish.
Step 1
Download the OpenCV source from their official git repository. You can choose to download any one of them. In my case I went for this one
Step 2
Setup Mingw-w64. In case you had trouble finding the link. Look here . Go for the link that says Online Installer for MinGW-GW64. Direct link , may break in future.
- Install MinGW-GW64 with the following setting
Make sure posix is selected. Otherwise the OpenCV installation will fail with unable to find mutex error. Which is part of pthreads library and specs. Architecture can be x86(32/64 bit machin) or x86_64(64bit machine) based on your working system.
2. Click next configure path of installation and let the binaries install.
3. After installation make sure to include MinGW bin folder in your path. It should be inside “..basePath/x86_64–8.1.0-posix***/mingw64/bin”
After this just test the installation by opening a terminal and type command “g++ — version”. If it says command not found. It could not get the path ,path was not set right, restart terminal or the machine. It should work! Google for the same !
Step 3
Once done install Cmake. Open Cmake and do the following
- Choose a source code path and a binaries path. Make sure they are separate.
2. Once done click on configure.A dialogue box will appear select MinGW Makefiles. This will make sure that the OpenCV new makefiles are compatible to mingw.
3. Click Finish. Let it generate some stuff. At this stage you should have some list of options to tick on. I did not needed any special attention to any of those options. So go on and click on Generate. Match the output from below, it should say “Configuration done” and “Generating done”
Step 4
Remember we chose a binaries folder, keep that in mind. Now navigate to that folder and open a terminal. In my case the folder I will have to navigate is.
“ C:\Users\Asus\Desktop\opencv”. Open a terminal in this folder. I use git-bash and you can use too. hit command “mingw32-make install” and pray that it builds hopefully. Because if it does my tutorial was successful.
After it’s done it should look like this. Also C++ compilation process takes a lot of time, LOT OF TIME . There are conference discussion on the same !! So you understand how serious is this problem.
At this point a new folder install will be created in your targeted build folder. We are concerned with the contents of this folder. So let’s do one thing. Lets move our build folder to “C:” drive root path that contains the install folder also. Now we add the binary path. Refer from the above image. In the environment variable there is a second path that points at the bin folder add that to environment variable also. Path “ C:\opencv\install\x64\mingw\bin” must be included in environment variable. This was in our case. These paths are IMPORTANT . 😧 Make sure it is there. The bin folder consist of all the various compiled binaries that are required for our OpenCV C++ compiled application. So you can choose to ship your application but then you will require the dll inside the bin to be shipped with your application also. Also since they are dll you cannot statically link them. So “-static” does not works. At least I could not get it done.
Step 5
Write a program
Now once you have the code copied. It’s time to test the installation. Remember to change the image location to your target image. Make sure you do that otherwise empty Mat will be created.
Double check that the include ,lib and bin folder of the install folder are targeted by your g++ compilation command.
If your command worked with no error. If there are linker errors then would advice to check whether linked dll are existing in the folder included by the command.
So hopefully you got a similar out put of size of the image currently being used.
Hope this tutorial helps you start your journey into the rabbit hole of C++ and Computer Vision. For more such content to follow this blog and if you found this helpful maybe a few claps. 😄 ….
Hopefully in the next version we will try to support cuda for Opencv DNN module.
How to compile makefile using MinGW?
I’m new to this. Just wanted to ask how to compile a makefile. I am using MinGW compiler in C language. Do I have to save all my files in MinGW\bin? because right now my files are in a different directory.
Appreciate the help.
6 Answers 6
What’s the difference between make and mingw32-make?
The «native» (i.e.: MSVCRT dependent) port of make is lacking in some functionality and has modified functionality due to the lack of POSIX on Win32. There also exists a version of make in the MSYS distribution that is dependent on the MSYS runtime. This port operates more as make was intended to operate and gives less headaches during execution. Based on this, the MinGW developers/maintainers/packagers decided it would be best to rename the native version so that both the «native» version and the MSYS version could be present at the same time without file name collision.
So,look into C:\MinGW\bin directory and first make sure what make executable, have you installed.(make.exe or mingw32-make.exe)
Before using MinGW, you should add C:\MinGW\bin; to the PATH environment variable using the instructions mentioned at http://www.mingw.org/wiki/Getting_Started/
Then cd to your directory, where you have the makefile and Try using mingw32-make.exe makefile.in or simply make.exe makefile.in (depending on executables in C:\MinGW\bin).
If you want a GUI based solution, install DevCPP IDE and then re-make.