Cross compiling from linux to windows

Кросскомпиляция из под Linux на Windows C++ gtk3

Я скачал mingw на Linux и скомпилировал обычный Hello, world! для Windows всё получилось!

Но мне нужно скомпилировать с библиотекой gtk+-3.0:

widget.hpp:1:10: fatal error: gtk-3.0/gtk/gtk.h: No such file or directory 1 | #include

Вопрос, как мне подключить gtk+-3.0.

2 ответа 2

GTK3 для винды есть в репозиториях MSYS2. Сам MSYS2 не работает под Wine, но пакеты можно скачать и распаковать вручную (но придется вручную определять и ставить зависимости их тех же репозиториев — это долго).

На правах саморекламы: я сделал скрипты, которые автоматически качают пакеты из этих репозиториев вместе с нужными зависимостями, и заодно вписывают пути к ним в нужные переменные окружения.

Инструкции по использованию есть в readme.

Минимальный пример выглядит так:

Читаем readme, ставим необходимые программы. На данный момент нужны make , wget , tar , zstd .

Устанавливаем сами скрипты, и качаем ими пакеты.

Все устанавливается в текущую папку. Никакого мусора нигде не остается, эту папку потом можно просто стереть.

Теперь ставим нужные переменные окружения командой source env/vars.src .

Компилируем почти так же, но передаем в pkg-config флажок —define-prefix .

Результат работает под вайном.

Флажок нужен потому, что в .pc -файлах (из которых pkg-config берет флаги) этих пакетов пути написаны с расчетом на то, что пакеты стоят в /mingw64 , а у нас это не так. Этот флажок исправляет пути на настоящие.

Вместо этого флажка надежнее будет сделать /mingw64 ссылкой: (путь поменяйте на тот, куда клонировали репозиторий)

Но можно сделать еще лучше.

По крайней мере в репозиториях убунты x86_64-w64-mingw32-gcc — слегка старый, 9.x. А вот репозиториях MSYS2 есть новенький GCC, который прекрасно работает под Вайном, но работает медленно.

Есть отличный вариант: поставить MSYS2 GCC только ради библиотек, которые идут с ним в комплекте, а кросс-компилировать уже Clang-ом, с помощью этих библиотек. Любая сборка Clang-а (в отличие от GCC) умеет кросс-компилировать под любую поддерживаемую архитектуру, поэтому просто ставим обычный Clang для линукса.

Дальше ставим пакеты:

На всякий случай делаем /mingw64 ссылкой (нужно исправить путь на свой, см. выше зачем нужна ссылка):

Теперь запускаем env/shell.sh , и если все сделано правильно, то кланг должен запускаться командами win-clang и win-clang++ , сразу со всеми флажками, нужными для кросс-компиляции.

Предупреждение: env/shell.sh кроме прочего настраивает ядро для прозрачного запуска экзешников через Wine (в консоли будут работать вещи типа ./foo.exe ). Эта настройка сохраняется до ребута.

Для этого скрипт спросит пароль для sudo . Если рандомным скриптам из интернета нет доверия, то можно отказаться вводить пароль (Ctrl+C), ввести ту же команду руками, потом набрать sudo -k — чтобы sudo забыл только что введенный пароль, чтобы скрипт ничего не выполнил с этим сохраненным паролем. А потом перезапустить скрипт.

Читайте также:  Восстановление tcp ip windows 10

Boost — cross compile — “from Linux” “to Windows”

I have downloaded «boost» (1.40.0) source code from their homepage «www.boost.org». I have Linux (Ubuntu 9.04 Jaunty) installed and trying to compile the boost libraries to the «WINDOWS» version (e.g. «.dll», NOT «.so») from my «LINUX» machine.

And now an important question:

IS IT POSSIBLE TO COMPILE TO THE «WINDOWS» BOOST LIBRARIES FROM «LINUX» (if someone say «yes» I will trust him only if he has already done it before of will write here a solution which will work for me. Sorry for that pessimism but I am trying to do this about for 3 days and nothing positive so far)?

So far I have compiled c++ programs this way. For compiling from Linux to Linux I have used «gcc» (or «g++») compiler. For compiling from Linux to Windows I have used «i586-mingw32msvc-gcc» (or «i568-mingw32msvc-g++») compiler (which is contained in «mingw32» package for «Ubuntu» for example).

So this strategy I have wanted to use also to compile boost libraries and I have tried this so far (after reading the «Getting started» article on the boost homepage):

—1. I have run «bootstrap.sh» from the «root» boost source code directory:

—2. Then I have changed one thing in the file «project-config.jam» (from «using gcc ;»):

—3. And finally run «bjam» executable:

But instead of creation of the «Windows» version of the boost libraries I got lots of error-messages.

Cross Compile to Windows From Linux

Why did I not know about this? It’s like I just discovered the screw driver!

Granted, this isn’t a silver bullet, but rather a quick way to get a Windows build of platform independent code that you might already have running in Linux. I’ve found that this approach makes it easy to get binaries out the door in a hurry when it’s hard to get a project building with Visual Studio or even on the Windows platform itself (due to, say, a complex build system).

I cover some quick solutions to the most common caveats I’ve run into, below.

Caveats

MinGW GCC vc GCC: Not as Smart with Templates

Whatever the reason, the Debian-packaged mingw flavor of gcc has a tendency to omit the instantiation of templates in many cases leading to missing symbols when linking. For instance, something like the following might sometimes complain that variants of scale can’t be found on link,

A horrible (but effective) solution I’ve found is to push the compile along with a dead function containing references to the template instantiations that you need,

Читайте также:  Как разблокировать схемы питания windows 10

C/C++ Standard Library Dependencies

When compiling C projects, use -w64-mingw32-gcc . The resulting binary will depend on at least KERNEL32.DLL and whatever MSVCRT.DLL is on clients’ systems. Therefore, you’ll need to make sure clients have the Microsoft C Runtime installed to use your software.

When compiling a C++ project, you must use -w64-mingw32-g++ to at least link. Otherwise, you’ll find you are missing LIBSTDC++-6.DLL and/or LIBGCC_S_SJLJ-1.DLL .

When shipping a C++ project, you’ll need to include LIBSTDC++-6.DLL and/or LIBGCC_S_SJLJ-1.DLL with your install. You can grab these from your Linux install where you’re performing the build in the associated MinGW directory, e.g., /usr/lib/gcc/x86_64-w64-mingw32/4.6/ . Note that you can have gcc include these libraries statically by including the flags, -static-libgcc and -static-libstdc++ .

External Dependencies

If your project depends on external libraries, you’ll need them available on your Linux machine during your build. I give some quick notes for the case where you’d like to use a pre-built (mingw) windows library and specific notes for Boost.

Note that except for purely C external libraries, the libraries themselves must have been built with MinGW. The naming conventions of C++ symbols differ between MingGW and Visual Studio.

Getting a MinGW build going for each project you might want to use is different. tinc’s cross compilation page gives instructions for a few libraries that it requires. You’ll need to consult the documentation on a project-by-project basis for each of your dependencies.

Using a Prebuilt DLL From Windows (libpng)

LibPNG provides pre-built windows binaries (albeit ancient). To build with the library, download both the binary and developer packages and extract into the same directory. Do the same for zlib since LibPNG depends on it, as well.

To build, give the compiler access to the appropriate include directories and link to the seemingly static .dll.a files. Do not attempt to link to the .dll files. Recall that linking to DLL’s on Windows requires a .lib file at build-time; by convention (at least for GNU projects), these are named with a .dll.a extension,

Cross-Compiling wxWidgets code from Linux to Windows

I use Code::Blocks IDE with wxWidgets in Debian 8.9 Jessie (x86-64).
When I use the GNU GCC Compiler everything works fine thus compiling nice wxWidgets executable for Linux.
But I need to have my program working on Windows platforms so I have to do cross-compiling.
I have installed mingw32 and followed the cross-compiling instructions given here.
I did my wxWidgets build configuration as follows:

This is so because the MinGW compiler I have is i686-w64-mingw32 , located in the folder /usr/i686-w64-mingw32 , and wxWidgets version is 3.1. My compiler set-up in Code::Blocks should be correct because I managed to do cross-compiling for simple console applications and those run properly on Windows 10.0. But when it comes to wxWidgets applications there are several problems:

Читайте также:  Http windows microsoft internet explorer products home

The compiler gives me the error (it happens when —static is added to Other compiler options in the build options for the project):

Now since wx directory in question is in the path /usr/i686-w64-mingw32/include/wx-3.1 I added this path to the search directories for the project (the build target only for the moment). This worked fine to proceed further.
My compiler settings are: wx-config —host=i686-w64-mingw32 —static —cflags

The compiler swears again (not surprised though :-)):

Ok I’ve found this one in /usr/i686-w64-mingw32/lib/wx/include/i686-w64-mingw32-msw-unicode-static-3.1 , so added this path to the compiler search directories.

The linker is swearing this time (creeping on my nerves):

for the build target:

for the release target:

My linker settings are wx-config —host=i686-w64-mingw32 —static —libs

I tried hard to fix this with several different build options for the wxWidgets library but with no effect on the result. So please, someone help!

Cross-compiling from Linux to Windows with Clang

I am trying to cross-compile C applications from Linux (64 bit) to Windows (64 bit) using Clang. I read the page on cross-compilation, which wasn’t too helpful.

As a simple test, I have the following code in test.c :

My best guess so far is clang -o test -target x86_64-win64-?ABI? test.c . However, I have no idea what ABI Windows 64 bit uses. When I run clang with the target triple x86_64-win64-abcdefg , it seems to compile fine—that is, it finishes without error and results in something that is a somewhat-valid binary. That doesn’t make any sense, considering abcdefg is definitely not a valid ABI. The resulting binary is far too big for such a small program, and Windows seems to think it’s a 16-bit program (. ). Disassembling it reveals references to «linux» and «gnu», so it would seem Clang is not even trying to compile for Windows.

Targeting win32 ( x86_64-win32-. ABI. ) results in the following error message:

This error, if I’m not mistaken, is the result of it not knowing where to look for system files. I assume Clang does store Windows header files somewhere, since it claims to be able to cross-compile; but where? If it doesn’t, is there somewhere I can download them?

Is there a list of all the architectures, systems, and ABI’s Clang supports somewhere? The list on the cross-compilation page is not comprehensive.

The page also suggests using -mcpu=. , but a warning suggests that is outdated. Instead, as the warning recommends, I tried -mtune=x86_64 . This seems to have no effect. Is this even necessary, considering the architecture is specified in the target triple?

I have seen some literature that suggests I need lld , LLVM’s experimental linker. Is this the case? I have had some issues compiling lld, and would like to avoid it if possible.

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