- How to compile Windows Visual C++ code on Linux
- How to Compile Linux Programs Under Windows with Cygwin
- Кросс-компиляция и отладка C++ Windows-приложения под Linux
- Wine, не юникодное приложение, английский интерфейс Ubuntu и русский язык
- Настройка IDE Code::Blocks для кросс-компиляции и отладки
- Линкование статической библиотеки boost’а
How to compile Windows Visual C++ code on Linux
Note: The intent of this question was to find if there exists a standard way of developing in VC for Windows and porting that code smoothly (meaning, making as few edits to the code as possible) over to a Linux system so that it can be compiled into an executable and run.
Based on the answers I’ve received I can see that there is a misunderstanding. Therefore, I’m going to break this question into two separate questions. One being my original (revised question) and the other being my specific issues and how to fix it. (I’ll add the links to this question once they’re posted).
Note: I’m pretty new to C++ and compiling with makefiles.
I’ve been creating a C++ program that will run on a Linux server and so far I’ve been using Visual Studio (Window’s current release) to write all the code. To be safe, before I started writing my program I attempted to create some basic C++ files in VC, transfer them over to my server then compile them with g++ and run the executable. Everything worked out so I thought:
«Hey, I can go ahead and write my entire program, follow the same process and everything will be fine!»
Clearly, I was wrong and that’s why I’m here.
When I run my makefile I get dozens of errors and I’m not exactly sure how to approach the situation. A large number of the error messages seem to be hinting at my use of vectors (which of course, run fine when compiling with VC).
I’ve had a look at the following questions:
But I can’t really find a direct solution to my issue (for example I’d prefer to avoid installing VC on a Linux platform and just working from there).
I’ve also looked into (and tried using) wineg++ but it didn’t seem to change anything upon compilation.
How should I go about this issue?
Meaning: Is it common practice to develop on Windows VC then port over to Linux? If so, is there a standard way of ensuring that everything goes smoothly? Or is it just a matter of knowing how your compiler on Linux works and coding appropriately so that no errors occur?
Preferably a solution that allows me to keep developing on Windows and simply port over everything to Linux when I’m done. Also if possible, try to make any answers as simple as possible, I’m still very amateur when it comes to most of this stuff.
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.
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.
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”:
Now unpack the archive file:
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.
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.
Run the following command, noting the inclusion of “-liconv” at the end:
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.
Кросс-компиляция и отладка C++ Windows-приложения под Linux
Показали мне недавно интересное приложение, под которое можно разрабатывать плагины. Приложение оказалось очень полезным для научной работы, но вот незадача — приложение разработано под Windows, у меня стоит Ubuntu. Windows для разработки под это приложение от лаборатории получить пока не удалось. Чтобы не тратить время, решил освоить кросс-компиляцию и отладку этого приложения.
Итого, имеется:
Ubuntu 12.10 x64
Не-юникодное приложение Мастерская Граф-Моделей (МГМ) (В командах консоли будет называться gmw.exe)
Нужно:
Разрабатывать и отлаживать плагины (dll-библиотеки), не устанавливая Windows.
И тут нам помогут Wine, Code::Blocks, портированное GDB, и boost.
Wine, не юникодное приложение, английский интерфейс Ubuntu и русский язык
При попытке открыть не юникодное приложение под Wine
получаются зюки следующего вида:
На эту проблему интернет очень быстро дает следующую подсказку:
В моём случае, данный подход не улучшил ситуацию ни на йоту.
Как выяснилось, русских локалей в системе не было добавлено (тыц).
Теперь запускаем с выше-указанной подсказкой
И, вуаля, запускается приложение с читаемым русским текстом:
Настройка IDE Code::Blocks для кросс-компиляции и отладки
Установка Code::Blocks
В дальнейшем для отладки нам потребуется менять код плагина отладки поэтому лучше сразу взять версию Code::Blocks из под svn.
Устанавливаем svn:
С помощью svn получаем код C::B, для этого переходим в папку, в которую хотим сохранить код C::B, где и набираем:
Переходим в полученную папку ‘trunk’.
Компиляция C::B происходит с помощью g++, autotools, automake и некоторых других утилит, которые необходимо установить:
Кроме того Code::Blocks зависит от wxWidgets:
Подстраиваем установщик под компьютер (можно запускать единожды):
И дальше, устанавливаем сам codeblocks (ключ —prefix можно упустить для использования настроек по-умолчанию):
Более подробно можно посмотреть по ссылке.
Настройка компиляции и линковки
Выполняем пункты с 1 по 5 с форума Code::Blocks. После этого компиляция программ должна работать, если не используется линковка к платформо-зависмым библиотекам (линковка с boost::regexp будет рассмотрена позже).
(*) В новом Code::Blocks немного изменилось меню по сравнению с инструкцией. Настройки искать нужно в ‘Settings->Compiler. ‘. Для старого Code::Blocks (10.05) пункт 5 нужно выполнить полностью, для нового же (12.11) настройку касающуюся gdb в 5 пункте пока трогать не будем.
Если используется boost его лучше положить отдельно от /usr/include, т.к. по этому адресу лежит много linux-специфичных заголовочных файлов, которые мы не хотим включать в проект при компиляции под Windows.
UPD: При настройке линковки в поле «Other Linker Options» имеет смысл добавить опцию «-Wl,—subsystem,windows,—kill-at», которая помечает, что это реально Windows DLL, и, что самое главное, запрещает использовать декорирование символов (—kill-at) при экспорте функций с соглашением вызова __stdcall. Подрбнее здесь и здесь.
Начиная с пункта 7 по ссылке выше, описывается кросс-отладка, но, к сожалению, insight.exe, упоминающийся в инструкциях, найти не удается. Поэтому пойдем своим путем.
Кросс-отладка в Code::Blocks & MingW32 gdb для Windows
gdb, который является родным для линукса частично умеет отлаживать Windows приложения, правда, умеет он только останавливаться на исключениях и почти всегда игнорирует точки останова. Чтобы справиться с этими проблемами скачиваем gdb в пакете mingw32 под Windows. Для этого скачиваем и затем распаковываем и переходим в подпапку ‘bin’. Устанавливаем gdb под Windows:
Теперь в этой же папке bin появился файл gdb.exe, он-то нам и нужен.
Создаем скрипт для имитации обычного gdb для этого в файл /usr/bin/i586-mingw32msvc-gdb
Заносим следующие строки:
Для старого C::B все уже настроенно, для нового же отладчик нужно настроить дополнительно. В пункте ‘Settings->Debugger’ кликаем по ‘GDB/CDB debugger’ затем по ‘Create Config’. В новом конфиге меняем команду запуска отладчика на ‘/usr/bin/i586-mingw32msvc-gdb’, остальные настройки по желанию. После этого идем в ‘Settings->Compiler. «, в пункте ‘Selected Compiler’ выбираем тот компилятор, который настраивали до этого и затем на вкладке ‘Toolchain executables’ меняем ‘Debugger’ на наш свежесозданный конфиг. Теперь отладчик будет останавливаться на точках останова, хотя и остановить программу в произволльный момент не сможет (данная проблема пока еще не решена). Правда при попытке отладить,C::B выдает следующую ошибку:
Эта ошибка говорит о том, что плагин отладчика в C::B не понимает выдачу отладчика gdb.exe. Как выяснилось при ближайшем рассмотрении плагин отладчика имеет платформо-зависимый код, и вот тут-то и нужно вспомнить что у нас есть исходники C::B. Мы сейчас слегка подкоррекируем код этого плагина. Нужно будет поменять код только одного файла ‘
Для этого нужно перейти в корень проекта C::B (откуда запускалась команды ./bootstrap), по умолчанию это папка ‘trunk’. И накактить патч:
Ну и пересобираем Code::Blocks:
И почти все готово, остается только создать проект. Шаги 12-13 по ссылке. Если же вы хотите создать проект dll-библиотеки, то указывайти создание динамической библиотеки в мастере и переименовывайте разширение в dll.
Проверям, что в настройках проекта стоит выбранная нами цепь компилятор-линкер-отладчик. ‘<Правая клавиша на проект>-Build Options. ‘ пункт ‘Selected compiler’, и можно радоваться и отлаживаться. Напомню, что по какой-то причине отладчик не может быть прерван во время исполнения, т.е. все отладочные действия могут буть применены только во время останова программы. В частности нельзя поставить новую точку останова, если программа не стоит на какой-либо другой точке останова…
Линкование статической библиотеки boost’а
Библиотека boost в основном является набором заголовочных файлов, и потому никаких проблем с линковкой обычно не возникает. Но для некоторых частей boost’а необходимо линковаться к статической библиотеке, например, boost::regex. Пробуем собрать проект и получаем:
Ошибка возникает из-за того, что мы пытаемся прилинковаться к linux билиотеке, для того чтобы построить windows-приложение.
Чтобы слинковаться нужно скомпилировать boost::regex с помощью MingW32 (про кросс-компиляцию). Скачиваем boost, распаковываем и переходим в папку с распаковынным boost’ом. Создаем файл user-config.jam в корне домашней директории:
Со следующим содержанием:
Дальше настраиваем сборку и собираем:
После выполнения последней команды у меня были ошибки «failed updating 1 target», что, правда, не мешает собираться программам.
В результате, у нас есть полностью подготовленная среда для написания, сборки и отладки Windows-приложений или Windows-библиотек из под Linux. Теперь можно приступать к работе…