Compile exe from linux

How to compile for Windows on Linux with gcc/g++?

So I was wondering if it is possible to have g++ make static compiled Windows executables that contains everything needed? I don’t have Windows, so it would be really cool, if I could do that on Linux 🙂

@AndiDog, «First dose for free», right. Anyway, setting up automated build process on Windows machine, while you have a completed and working one for Linux, is unnecessary.

@el.pescado, building and testing are completely different tasks. Windows is unnecessary for the former.

7 Answers 7

mingw32 exists as a package for Linux. You can cross-compile and -link Windows applications with it. There’s a tutorial here at the Code::Blocks forum. Mind that the command changes to x86_64-w64-mingw32-gcc-win32 , for example.

Ubuntu, for example, has MinGW in its repositories:

$ apt-cache search mingw [. ] g++-mingw-w64 - GNU C++ compiler for MinGW-w64 gcc-mingw-w64 - GNU C compiler for MinGW-w64 mingw-w64 - Development environment targeting 32- and 64-bit Windows [. ] 

If you use debian, mingw32 is already in the repository, together with few precompiled libraries too.

Well, there’s a cross-compilation environment at nongnu.org/mingw-cross-env. It includes freeglut, for example. But I haven’t used this, so don’t ask me about it 😉

Does the «32» in mingw32 mean that I can only produce a 32-bit binary? Is there a solution to produce a 64-bit binary as well?

bluenote10: there are variants that build for x64, such as «x86_64-w64-mingw32-g++». The base «mingw32» may or may not be capable, but it’s easy enough to install/use the variants by name. ar2015: Does it not support C++11 at all or are you talking about a problem you had with it? I’m working on getting a project to build with mingw as we speak and this would be good information to know. Other threads indicate that it does support c++11 (e.g. stackoverflow.com/questions/16136142/…). Of course I’d be happy to help, but a separate post would be best for that.

Suggested method gave me error on Ubuntu 16.04: E: Unable to locate package mingw32

To install this package on Ubuntu please use following:

sudo apt-get install mingw-w64 

After install you can use it:

For 64-bit use: x86_64-w64-mingw32-g++

For 32-bit use: i686-w64-mingw32-g++

I tried. It just throws all sort of errors regarding DWORD, LPVOID, WORD, BYTE and so on. Isn’t doing anything cross-compilation

@RichardMcFriendOluwamuyiwa Looks like you missed some headers to compile it on linux. It could generate binaries for running on Win machine. Please update your sources.

Читайте также:  Все пользователи линукс через терминал

I made it work by including the windows.h before the winbase.h header. VS code was automatically rearranging the includes and leading to error so I had to force the order by empty comment lines

One option of compiling for Windows in Linux is via mingw. I found a very helpful tutorial here.

To install mingw32 on Debian based systems, run the following command:
sudo apt-get install mingw32

To compile your code, you can use something like:
i586-mingw32msvc-g++ -o myApp.exe myApp.cpp

You’ll sometimes want to test the new Windows application directly in Linux. You can use wine for that, although you should always keep in mind that wine could have bugs. This means that you might not be sure that a bug is in wine, your program, or both, so only use wine for general testing.

To install wine, run:
sudo apt-get install wine

Источник

Создать exe-файл в Linux с использованием cmake

Необходимо под Linux системой (Ubuntu 17) собрать проект с использованием cmake. Как можно это реализовать, и если это недопустимо, то как это добиться успеха используя какой-нибудь кросс-компилятор (например, mingw), если нужно при этом подключить библиотеки. С использованием mingw возникли проблемы, при запуске полупустого проекта возникает ошибка «Отсутствие библиотеки libstdc++6. «

фактически дубликаты: 1, 2 и 3. указывать нужный компилятор проще всего переменной окружения: CXX=/путь/к/компилятору-c++ команда

1 ответ 1

Если Ваш проект чисто собирается под линуксом и у Вас установлен mingw32 или mingw64, сделайте следующее:

1) создайте отдельный каталог для сборки проекта под виндовсы в каталоге, где- лежит Ваш CMakeLists.txt и зайдите в него

2) запустите генератор, который создаст Makefie-иерархию для кросс-компилятора mingw

$ cmake -DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-mingw32.cmake .. 
$ cmake -DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-mingw64.cmake .. 

(Путь к тулчейну отредактируйте как нужно в Вашей системе)

4) если все прошло как надо, проверьте работу под wine

5) если под wine работает, соберите под виндовсы пакет с необходимым рантаймом — для запуска под живыми виндовсами кроме самой программы нужно взять .dll-и, что лежат в /usr/x86_64-w64-mingw32/sys-root/mingw/bin или /usr/i686-w64-mingw32/sys-root/mingw/bin (Это у меня в федоре они там, где у Вас, не знаю — посмотрите сами)

libatomic-1.dll libgcc_s_seh-1.dll libgsl-0.dll libgslcblas-0.dll libssp-0.dll libstdc++-6.dll libwinpthread-1.dll 

Выберите из них те, на отсутствие которых ругается загрузчик при запуске вашей программы под виндовсами, и положите рядом с исполняемым файлом.

Для сборки, используя MSVC, нужно собирать под виндовсами. Процесс выглядит так:

1) Открываем cmd-среду из установленных в меню Программы при установке MSVCxx

2) переходим в каталог сборки (предполагаем, что он в создан каталоге, где лежит Ваш CMakeLists.txt)

или указывая генератор явно, если рабочая платформа не целевая (кросскомпиляция)

Читайте также:  Adguard home linux настройка

> cmake -G «Visual Studio xx Win64» ..

В CMakeLists.txt следует указать, что Вы не будете использовать _s() шлак, который MS ввела в свой компилятор с целью разрушения стандарта C++, поскольку адекватную реализацию его она осилить не в состоянии. Я использую следующее:

if (MSVC) set(CMAKE_EXE_LINKER_FLAGS "$ /NODEFAULTLIB:LIBCMT") add_definitions(/W4 /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127) add_definitions(/D _CRT_SECURE_NO_WARNINGS) elseif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUC) add_definitions(-Wall -W) else () message ("Unknown compiler") endif () 

Источник

Compile Windows C console applications in Linux

Best answer so far, and yes, there was a dupe 😀 Also nice to post the needed packages. Straight answer, to the punch.

Thanks for the answer. Also sorry for the duplicate question, I didn’t spot it. 🙂 Keep up the good work! Thanks again.

On Fedora, we also have resources for learning about compiling for win32 using mingw, an irc channel, the mingw32 utilities and a bunch of pre-built libraries for windows — for more info, see: fedoraproject.org/wiki/SIGs/MinGW .

You can if it’s standard C, and doesn’t use Windows libraries.

C code itself is very portable, and the standard C libraries (libc) are available pretty much everywhere. If your code does printf() and sscanf() and fopen() and so on, then it will just compile and run on another platform. Windows, Linux, BSD, etc.

It’s the libraries other than libc that introduce portability challenges.

Anything that links with Windows-specific platform libraries is trouble. Kernel32.lib, user32.lib, etc etc.

There are third-party libs, too, that, if written in C, should be available across Linux and Windows. PCRE is a good example here — it’s a Regular Expression library written in C, and it’s available on Windows as well as on Linux. there are literally hundreds of libraries in this set.

If you confine yourself to libc and library calls into portable libs, then you will have a portable C application.

Источник

Сборка .exe из под Linux

Доброго времени суток товарищи кодеры, а кодерам линуксоидам вдвойне!
Меня интересует седующий вопрос:
Каким способом наиболее эффективно собрать код в exe-шник?
Имеется в виду не просто сборка с заданным разширением, но и работоспособность в осях Win. Как консольные, так и проги с собственным интерфейсом.
Как это делаете вы? Если делаете.
Использовать виртуальную машину или поставить Win не имею возможности.
Что если через установить например VS или Delphi, запускать это wine’ом, писать на них с использованием библиотек WinAPI и как результат собирать, то будет ли полученный файл юзабелен под Windows?
Если вы посоветуете кроссплатформенный компилятор, то накидайте небольшое HowTo или линк на него пожалуйста.

5 ответов 5

Что если через установить например VS или Delphi, запускать это wine’ом, писать на них с использованием библиотек WinAPI и как результат собирать, то будет ли полученный файл юзабелен под Windows?

Да, это возможно. Получаемый исполняемый файл будет такой же как при сборке под Windows. Единственный нюанс связан с тем, что VS и Delphi являются серьезными программными комплексами и их произвольная версия с произвольной версией wine и linux может быть просто неработоспособна. Но с достаточно старыми и ‘зрелыми’ версиями студий проблем не будет.

Каким способом наиболее эффективно собрать код в exe-шник?

Компилятором, поддерживающим кросс-компиляцию. Это означает, что компилятор будет под linux, а выходной код — под windows. Ищите в гугле по ключевым словам gcc, cross-compile, windows. Еще рекомендую обратить внимание на проекты Mingw32 и Cygwin: они позволяют писать программы под windows с помощью gcc, т.е. можно делать переносимые программы между средами linux и windows с одним исходным кодом, путем простой перекомпиляции.

Читайте также:  Astra linux oracle database

Источник

How to compile C code in Linux to run on Windows? [duplicate]

I am using Linux/GNU GCC to compile C source code. Is there any way I can generate .exe files for Windows running on x86 or x64 architecture? The compiled code needs to be generated on the Linux machine.

The compiler is machine dependent. So I am guessing you will have to download windows version of gcc to properly compile your source code into a windows executable file.

4 Answers 4

You would need a cross-compiler to create a Windows executable in Linux.

Mingw-w64 is an advancement of the original mingw.org project, created to support the GCC compiler on Windows systems.

Installing the cross-compilation

sudo apt-get install mingw-w64 
i686-w64-mingw32-gcc -o test.exe test.c 
x86_64-w64-mingw32-gcc -o test.exe test.c 

Interesting. I’ve just naively tried this on one of my projects that uses libcsv , which I have installed on my Linux machine. However, attempting to compile it gives me: fatal error: csv.h: No such file or directory — would you have any insights or articles on how to deal with such issues when using Mingw-w64?

You need a cross compiler: A compiler that targets another system than it runs on.

A gcc targeting windows comes in the mingw package and can also be compiled to run on Linux, and many Linux distributions already have packages containing it, so just search your package management tools for «mingw».

Cross compilers have by convention the name of the system they target prepended to their name, so the variant of gcc for compiling windows executables will probably be named something like i686-w64-mingw32-gcc , but this might differ depending on the packages provided by your Linux distribution.

Источник

Оцените статью
Adblock
detector