Compile linux applications on windows

Run C program written in Linux on Windows

I have C program which I wrote in Linux that runs very well. Now I want to run it on Windows. How do I easily run it on Windows?

Does it include any code that is specific to Linux? Or does it use only C standard library and POSIX API?

4 Answers 4

Elaborating a bit on the answers from caf and jartieda.

Cygwin is an attempt to emulate a (nearly) complete POSIX execution environment in a native Windows process. It is complete enough that a surprising amount of Unix application code simply compiles and runs using the familiar ./configure && make && make install idiom. This trick was done by supplying a DLL that emulates POSIX system calls using the Windows API. Based on that, you get a complete GCC toolchain, bash, and all the usual command line utilities you are used to. One downside is that the compiled program is dependent on the Cygwin DLL, which makes it tricky to deliver the result to a system that does not already have Cygwin installed and whose user doesn’t want to use a Unix shell.

MinGW is a port of the GCC toolchain that generates native Windows applications that depend on the well known (and distributed with Windows itself) MSVCRT.DLL C runtime library. It makes no attempt to emulate a POSIX operating system, but applications that are mostly based on the standard C libraries, will often build essentially unchanged.

MSYS is a compile-time environment that provides enough Unix utilities (including bash) to often allow ./configure to run, and if the project supports the results, finish the build with MinGW’s GCC. The result is a native Windows executable that does not depend on any DLLs you don’t deliberately use aside from MSVCRT.DLL. Although the MSYS environment itself was a fork of an early version of the Cygwin project, it is primarily intended to be used to provide a unix-like place to compile native Windows applications: one would generally not build new applications based on its runtime environment.

Another approach to compiling for Windows is to use the MinGW cross compiler on linux. A number of MinGW’s core developers work that way, testing they product either under Wine, or under Windows running in a VM or a separate PC.

If the program has a GUI component, then you may have additional difficulties. Some GUI frameworks are available for both Linux and Windows. Qt, wxWidgets, and IUP all leap to mind, but there are others out there.

Edit: I’ve improved the paragraph above about MSYS to emphasize that it is intended to be a compile-time environment for building programs that run as native Windows applications, and not a full POSIX environment like Cygwin.

Note, also, that there is always the option of porting the project to one of the more traditional compilers for Windows development. Open Watcom, the Borland compilers, and Microsoft all have free or inexpensive versions, although often enough not under licenses that make the opens source community entirely happy.

Читайте также:  Giving root permission user linux

This approach probably requires more effort because the differences between a Linux environment and the Windows environment become more visible when you also switch from one toolchain to another. This is especially true of the Microsoft compilers which are historically not as fully standards compliant as GCC.

Источник

How to cross compile from windows g++ cygwin to get linux executable file [duplicate]

I have an updated cygwin-full install ,mingw ,codeblocks on a windows system. i have a c++ program which performs xml generation based on input. I understand to build an executable file for unix we use makefiles. makefiles being typical project files . Hence i used the plugin cbp2make.exe to get the makefile for the cbp project file. and i tried to execute make in cygwin. hoping to get a linux executable file. but this was clearly wrong. a typical test c++ test program test.c would be compiled in cygwin using gcc cross compile options like.

this would give us the linux executable file test or if no name is specified it would give an a.out This is all well and good for a simple c++ program with no included header files. I understand when we are dealing with c++ files with lot of external library files a simple g++ -o ourprojfile.exe ourprojectfile.cpp does not work hence we would need to use make files. Question 1 : Am i wrong in assuming this ?* Question 2: how can we setup cross compile to get a linux executable file directly from codeblocks. Update : the problem at my end seems to be missing dependent cpp files which i assumed i included in the main file. The solution was to include them in the main file or simply write handle like so

g++-linux myprog_linux main.cpp first.cpp second.cpp third.cpp 

The problem now is after i get the Linux executable file. when i try to run it on linux machine i get the error of a

 /usr/local/folder/myfile/my_prog_nix: error while loading shared libraries: libstdc++.so.5: cannot open shared object file: No such file or directory 

Источник

Запуск программ Linux в Windows

Для запуска программы Linux в Windows возможны следующие варианты:

  • Запуск программы «как есть» в подсистеме Windows для Linux (WSL). В WSL программа выполняется непосредственно на оборудовании компьютера, а не на виртуальной машине. WSL также поддерживает прямые вызовы файловой системы между системами Windows и Linux, устраняя необходимость в SSL-транспорте. WSL разработана как среда командной строки и не рекомендуется для приложений, интенсивно использующих графику. Дополнительные сведения см. в документации по подсистеме Windows для Linux.
  • Запуск программы «как есть» на виртуальной машине Linux или в контейнере Docker на локальном компьютере или в Azure. Дополнительные сведения см. в разделах Виртуальные машины и Docker в Azure.
  • Компиляция программы с использованием gcc или clang в средах MinGW или MinGW-w64, которые предоставляют слой преобразования системных вызовов Linux в системные вызовы Windows.
  • Компиляция и запуск программы с использованием gcc или clang в среде Cygwin, которая предоставляет более полную среду Linux в Windows по сравнению с MinGW или MinGW-w64.
  • Ручное портирование кода из Linux и компиляция для Windows с использованием Microsoft C++ (MSVC). Этот подход подразумевает рефакторинг кода, не зависящего от платформы, в отдельные библиотеки, и последующее переписывание специализированного кода, относящегося к Linux, в код для Windows (например, для API-интерфейсов Win32 или DirectX). Предположительно, этот вариант лучше всего подходит для приложений, в которых требуется высокопроизводительная графика.
Читайте также:  Linux централизованное хранение конфигов

Источник

How to Compile Linux Programs Under Windows with Cygwin

Windows and Linux are two very different systems, and as such, it often isn’t easy to port programs written for one to the other, especially when dealing with GUI programs. Although there are many different cross-platform libraries and SDKs, native programs written without portability in mind are quite hard to port.

When it comes to compiling and running programs written for Linux on Windows, there is a solution known as Cygwin. The Cygwin project is a collection of the most common tools and compilers (including the bash shell and the GNU compiler chain) for Windows. It also includes a library that provides a compatibility layer so that programs which call Linux specific APIs can be compiled. Cygwin isn’t an emulator or virtual machine, and it doesn’t allow Linux binaries to run on Windows without first being re-compiled.

Visit the Cygwin installation page and download the 32-bit or 64-bit setup executable (depending on which variant of Windows you are using). Execute the setup program. Click Next and Next again (to “Install from Internet”). The default directory is “C:\cygwin”. It can be changed if needed, but unless you have a specific reason to change it, the default is best. Click Next, Next and Next again.

The Cygwin project has mirror sites all over the world; pick one which you think will best serve your location and click Next. You now need to pick which packages to install. To compile simple Linux programs in Windows, you will need the GNU Compiler Chain (GCC) which provides a C and C++ compiler.

cygwin-select-packages

Type “gcc” in the search box and then click in the small plus sign next to “Devel” in the list of packages. Find “gcc-core” and “gcc-g++” and click “Skip” for each one. The word “Skip” will change into a version number and the “n/a” sign in the “Bin?” column will turn into a checked box. Type “make” in the search box and find “make” under “Devel.” Click “Skip” to mark it for install. Search for “wget” and also mark it for install from “Web.” To build the example below, we will also need “libiconv;” search for it and mark it for install.

cygwin-gcc-selection

Click Next. The installer will then see what other packages need to be installed to resolve any dependencies. Click Next to accept the recommendations.

Once all the packages have been downloaded and installed, follow the last steps until the installer exits. Start the “Cygwin Terminal” to enter into the Linux-like development environment. In the terminal you don’t use Windows commands like “dir” but rather shell commands like “ls”.

Читайте также:  Пользователь линукс имеет доступ

To demonstrate how to compile a Linux program under Windows, we will use the HTML-XML package from the W3. For a look at what it can do, see How to Manipulate HTML and XML Files from the Command Line.

Download the source files using “wget”:

wget http://www.w3.org/Tools/HTML-XML-utils/html-xml-utils-6.7.tar.gz

Now unpack the archive file:

tar -zxf html-xml-utils-6.7.tar.gz

The source files are now in the “html-xml-utils-6.7” directory. Enter that directory:

Before the files can be built, you need to run the “configure” shell script to generate the Makefile (the build instructions) which are suitable for this build environment. This is a common step on Linux (and Cygwin) when building packages from source.

cygwin-configure-html-utils

Once “configure” has finished, you can start the build using “make”:

The build will fail part way through. I was in two minds about what to do next. Either I could switch to another project and build that from its source or battle on with the HTML-XML-utils. I opted for the latter as it shows that not everything will be a walk-in-the-park when trying to compile Linux programs under Cygwin. The solution to this particular problem is simple. The error message shows that the linker is unable to find the “iconv” library. A quick look at the link command shows that the library isn’t specified. The quick and dirty solution is to run the command manually and tell the linker to use libconv. The “proper” way to fix this would be to start delving into the Makefile etc. to find out why it isn’t working.

cygwin-build-fails

Run the following command, noting the inclusion of “-liconv” at the end:

gcc -g -O2 -o hxindex.exe hxindex.o scan.o html.o openurl.o url.o heap.o class.o errexit.o connectsock.o types.o tree.o genid.o dtd.o headers.o dict.o fopencookie.o -liconv

Once the “hxindex.exe” file is built, you can continue with the rest of the build by typing “make” again. The way “make” works is it checks what has and has not been built, and then it continues the build process at the appropriate point. Since we have manually built “hxindex.exe”, “make” just carries on with the next binary in its list.

When “make” completes, you will have all the .exe files in the html-xml-utils-6.7 directory.

If you get stuck using Cygwin you should look at the FAQ, and at the documentation. Failing that, the project has a set of mailing lists. If you have any problems with the steps described above, then please use the comments section below.

Gary has been a technical writer, author and blogger since 2003. He is an expert in open source systems (including Linux), system administration, system security and networking protocols. He also knows several programming languages, as he was previously a software engineer for 10 years. He has a Bachelor of Science in business information systems from a UK University.

Our latest tutorials delivered straight to your inbox

Источник

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