Wxwidgets install on windows

Posted on October 5, 2022 by codvator | Windows Development

Using wxWidgets and Microsoft Visual Studio in creating C++ applications

Introduction

In tutorial, we basically review the process of building wxWidgets applications using Microsoft Visual Studio. It basically involves configuring Microsoft Visual Studio to see certain library dependencies for successful application builds.

There are but two kinds of applications that can be built in C++ or other programming languages. These are console based or GUI based. Console based applications  have no user interface and they typically use commands which are executed by a user over a command line like in the MS DOS.

On the other hand, GUI based applications employ user interfaces which receive user input, process the input and then update the application view as dictated by the application logic. Unfortunately, not all programming languages (like C++ and C) have in built GUI support  and so developers usually really on GUI libraries to add user interfaces to their applications. One of such libraries is wxWidgets.

So in this post, we are going to learn how to get started with wxWidgets, in the process, building a simple wxWidgets C++ application using Microsoft Visual Studio 2017.

What is wxWidgets

wxWidgets is a programmer’s toolkit for writing desktop or mobile applications with graphical user interfaces (GUIs). It’s a framework, in the sense that it does a lot of the housekeeping work and provides default application behavior. The wxWidgets library contains a large number of classes and methods for the programmer to use and customize.

Applications typically show windows containing standard controls, possibly drawing specialized images and graphics and responding to input from the mouse, keyboard, or other sources. They may also communicate with other processes or drive other programs.

In other words, wxWidgets makes it relatively easy for the programmer to write an application that does all the usual things modern applications do.

Installing and building wxWidgets

Before you go ahead, we assume you have already downloaded MS Visual Studio on your computer or else, download it from here and install it.

We shall now head over to the wxWidgets downloads page, to download a zipped version of the wxWidgets source code or a windows installer. Which ever method you use to install wxWidgets on your computer, just make sure you note the folder where the wxWidgets source code has been installed. For example, let us assume you installed it in the C drive: C:/wxWidgets-3.1.3

To build wxWidgets using MS Visual Studio, head over to the wxWidgets folder, our case (C:/wxWidgets-3.1.3) and follow through the directory structure; C:/wxWidgets-3.1.3/build/msw. Under the msw folder, you will find MS Visual studio solution files. Double click a solution file our case; wx_vc17.sln to open it using Microsoft Visual Studio.

Image of Microsoft Visual Studio after opening a solution file

Then build the opened solution to compile various versions of the wxWidgets library; the Debug, DLL Debug, DLL Release and lastly the Release

  1. To start this process; select the version to compile using the drop down menu in the tool bar
  2. Then go to menu item: Build > Build Solution.
  3. Click Build Solution to start the compilation process for the selected library version. This takes some time. So you need to wait.
  4. Repeat the steps 1-3, for all the four library versions
  5. After compiling wxWidgets, close MS Visual Studio

Creating a wxWidgets application in Microsoft Visual Studio

To create a simple C++ application, follow the steps below;

1. Open MS Visual Studio and then create a new project. Go to menu item: File > New > Project

2. A new project dialog window appears from which you will select: Visual C++ > Empty Project. Then you enter your project name and where you want to store your application.

A new project window in Microsoft Visual Studio

3. Click Ok. MS Visual Studio will then go on to create an empty project named SimpleApplication to which you will add C++ files.

The main application window of Microsoft Visual Studio after creating a new project

4. Then add a Main.cpp file to our new project. To do this, navigate to the solution explorer window document tree where there is a Source Files folder. Click on it to select it and then right click. A pop up menu opens. Go to menu item: Add > New Item. Click New Item. An add new item window appears from which you will name your file Main.cpp.

Adding a new class file to a project in Miscrosoft Visual Studio

5. Click Add to add the file to our project

Main project window of Miscrosoft Visual Studio after a class file is added to a project

6. Now, copy the C++ code below and add it to your Main.cpp file.


// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif

#define ID_MENU_HELLO   1 // Menu Item ID

//////////////////////////////////////////////////////////////////////////////////////////////////
/////  DECLARE THE APPLICATION'S MAIN FRAME WINDOW
//////////////////////////////////////////////////////////////////////////////////////////////////

class Frame : public wxFrame
{
public:
	Frame(const wxString& title, const wxPoint& pos, const wxSize& size);
private:
	void OnHello(wxCommandEvent& event);
	void OnExit (wxCommandEvent& event);
	void OnAbout(wxCommandEvent& event);
};

//////////////////////////////////////////////////////////////////////////////////////////////////
/////   DECLARE THE APPLICATION CLASS
//////////////////////////////////////////////////////////////////////////////////////////////////

class HelloWorld : public wxApp
{
public:
	// Define the initialization method
	// Its called on application start up
	virtual bool OnInit();
};

//////////////////////////////////////////////////////////////////////////////////////////////
///// IMPLEMENT THE OnInit() WHICH INITIALIZES THE APPLICATION                               
/////////////////////////////////////////////////////////////////////////////////////////////
bool HelloWorld::OnInit()
{
	// Create main application window
	Frame *frame = new Frame("Hello World", wxPoint(50, 50), wxSize(300, 300));

	// Display the frame window
	frame->Show(true);

	// Start the event loop
	return true;   
}

////////////////////////////////////////////////////////////////////////////////////////
///// START RUNNING THE APPLICATION 
////////////////////////////////////////////////////////////////////////////////////////

wxIMPLEMENT_APP(HelloWorld);

////////////////////////////////////////////////////////////////////////////////////////
///// IMPLEMENT THE FRAME (APP MAIN WINDOW) CONSTRUCTOR 
///////////////////////////////////////////////////////////////////////////////////////

Frame::Frame(const wxString& title, const wxPoint& pos, const wxSize& size)
	:wxFrame(NULL, wxID_ANY, title, pos, size)
{
	wxMenu *menuFile = new wxMenu;
	menuFile->Append(ID_MENU_HELLO, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item");
	menuFile->AppendSeparator();
	menuFile->Append(wxID_EXIT);

	wxMenu *menuHelp = new wxMenu;
	menuHelp->Append(wxID_ABOUT);

	wxMenuBar *menuBar = new wxMenuBar;
	menuBar->Append(menuFile, "&File");
	menuBar->Append(menuHelp, "&Help");

	SetMenuBar(menuBar);
	CreateStatusBar();
	SetStatusText("Welcome to wxWidgets!");

	// Register events for this frame
	Bind(wxEVT_MENU, &Frame::OnHello, this, ID_MENU_HELLO);
	Bind(wxEVT_MENU, &Frame::OnAbout, this, wxID_ABOUT   );
	Bind(wxEVT_MENU, &Frame::OnExit,  this, wxID_EXIT    );
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////    DEFINE EVENT HANDLERS FOR THE APPLICATION FRAME
///////////////////////////////////////////////////////////////////////////////////////////////////////////

// Event Handler for clicking the About Menu item
// Navigate to Help > About in the GUI app
void Frame::OnAbout(wxCommandEvent& event)
{
	wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION);
}

// Event Handler for clicking the Hello Menu item
// Naviaget to File > Hello in the GUI app
void Frame::OnHello(wxCommandEvent& event)
{
	wxLogMessage("Hello world from wxWidgets!");
}

// Event handler on clicking the Exit Menu item
// Navigate to File > Exit in the GUI app
void Frame::OnExit(wxCommandEvent& event)
{
	Close(true);
}

The Main.cpp file will have quite a number of errors since Visual Studio cannot recognize the code in the file. You will need to add wxWidgets dependencies to the project to remove these errors so that you can successfully compile your project.

Adding the necessary dependencies to build a wxWidgets application

This will basically involve adding wxWidgets dependencies to three build configurations in MS Visual Studio; all configurations, debug and release. We shall begin with all configurations properties.

All Configurations

  1. Go to menu item: Project > SimpleApplication Properties. Click SimpleApplication Properties to open the project property window. From the configuration drop down, select All Configurations.
  2. Go to Configuration Properties > C/C++ > General > Additional Include Directories > Edit > New Line and then navigate to the wxWidgets source code folder and add the include directory for my case: C:/wxWidgets-3.2.1/include. Then click Ok.
  3. Go to C/C++ > Preprocessor > Preprocesor Definitions > Edit. A dialog appears where you will add WXUSINGDLL into the text area and then click Ok.
  4. Go to Linker > Additional Library Directories > Edit > New Line and then navigate to the wxWidgets folder > lib > vc_dll (for my case: C:/wxWidgets-3.2.1/lib/vc_dll) to add the vc_dll library. Click Ok and Apply the changes.

Microsoft Visual Studio in an all configurations mode when adding wxWidgets library dependencies

Debug

  1. Under the configuration drop down, switch to Debug
  2. Go to C/C++ > General > Additional Include Directories > Edit > New Line and then navigate to the wxWidgets source code folder > lib > vc_dll > mswud to add the mswud library. Click Ok.
  3. Go to Linker > input > Additional Dependencies > Edit. A dialog appears where you will add the base library, wxbase32ud.lib and the core library, wxmsw32ud_core.lib. Note that the figure 32 in these library names will change depending on the version of wxWidgets you are using for example; version 3.1.3, it will be 31 and for version 3.2.1, it will be 32. To be certain, navigate to the wxWidgets source code folder > lib > vc_dll (for my case: C:/wxWidgets-3.2.1/lib/vc_dll) where these libraries are stored and take a look at their names.
  4. Then click Ok and Apply the changes.

Microsoft Visual Studio in the debug mode when adding wxWidgets library dependencies

Release

  1. Under the configuration drop down, switch to Release
  2. Go to C/C++ > General > Additional Include Directories > Edit > New Line and then navigate to the wxWidgets folder > lib > vc_dll > mswu to add the mswu library. Click Ok.
  3. Go to Linker > input > Additional Dependencies > Edit. A dialog appears where you will add the base library, wxbase32u.lib and the core library, wxmsw32u_core.lib. To be certain, go to the wxWidgets source code folder > lib > vc_dll (for my case: C:/wxWidgets-3.2.1/lib/vc_dll) where these libraries are stored and take a look at their names. Note that the figure 32 in these library names will change depending on the version of wxWidgets you are using. It’s also worth noting that the release and debug versions of the library files defer by just a d after that u. 
  4. Then click Ok and Apply the changes.

MVS in the realease mode when adding wxWidgets library dependencies

After adding these dependencies, you will notice that the errors we had in our Main.cpp file are gone. Should you run the application at this point by clicking the local windows debugger button, MS Visual studio will notify you with a system error showing that you are missing some .dll files.

So, to add the needed files, move to wxWidgets source code folder > lib > vc_dll. If you compiled a Debug version of your app in MS Visual Studio, copy and paste both the debug version core and base libraries, wxbase321ud_vc_custom.dll and wxmsw321ud_core_vc_custom.dll respectively to the Debug folder of your SimpleApplication. For a Release version, you will copy the wxbase321u_vc_custom.dll and wxmsw321u_core_vc_custom.dll respectively to the Release folder of your SimpleApplication. Now run the application and MS Visual Studio will display your GUI application.

Microsoft Visual Studio displaying the application GUI after a successful compiling process

OVERVIEW

In another blog post, we saw Setting up wxWidgets Environment for C++ in Windows 10 without having to use Visual Studio. The main problem with that method is that we have to take care of everything ourselves, specially the handling of make files. With that in mind, this blog post explains how to leverage Visual Studio to do wxWidgets development. Using an IDE not only makes things easier but faster as well.

This has been tested with Visual Studio 2022. There seem to be some issues if you try this with VS 2019 or older.

INSTALL VCPKG

What we need is a package called vcpkg which is an open source tool developed by Microsoft to help incorporate third-party C++ libraries and frameworks for use in VS. To do that. make sure you have Git installed in your system. Go to the Github repo for vcpkg. https://github.com/microsoft/vcpkg

In the command line, go to the directory of your choice eg. d:\projects and type in git clone https://github.com/microsoft/vcpkg.git

D:\projects>git clone https://github.com/microsoft/vcpkg.git
Cloning into 'vcpkg'...
remote: Enumerating objects: 158493, done.
remote: Counting objects: 100% (477/477), done.
remote: Compressing objects: 100% (257/257), done.
remote: Total 158493 (delta 275), reused 353 (delta 220), pack-reused 158016R
Receiving objects: 100% (158493/158493), 61.41 MiB | 3.80 MiB/s, done.
Resolving deltas: 100% (100285/100285), done.
Checking out files: 100% (9007/9007), done.

Now change the directory to vcpkg eg. cd vcpkg and run the following command:

bootstrap-vcpkg.bat

Now we are going to use vcpkg to setup wxWidgets for 64 bit Windows. To do that run

vcpkg install wxWidgets:x64-windows

This will take a while to install and setup.

Next we integrate wxWidgets libraries to work with Visual Studio via vcpkg. Use the following command:

vcpkg integrate install

The last step is to install the wxWidgets library now. Use the command

vcpkg install wxwidgets:x64-windows

Now we are ready to test out a wxWidgets program in Visual Studio

BUILD SAMPLE WXWIDGETS APPLICATION

  • Open Visual Studio. Choose a new Project Type as C++ Empty Windows Project (C++, Windows, Console)
  • Lets call the project as FourthProject. You can choose whatever name you like .
  • Under Header Files, create a new file FourthProject.h and put the following code:
#pragma once
class MyProjectApp : public wxApp
{
public:
    MyProjectApp();
    virtual ~MyProjectApp();
    virtual bool OnInit() override;
};
  • Under Source Files, create a new file FourthProject.cpp and put the following code:
#include <wx/wx.h>
#include "FourthProject.h"

MyProjectApp::MyProjectApp()
{
}

MyProjectApp::~MyProjectApp()
{
}

bool MyProjectApp::OnInit()
{
	wxFrame* mainFrame = new wxFrame(nullptr, wxID_ANY, L"MyProject");
	mainFrame->Show(true);
	return true;
}

wxIMPLEMENT_APP(MyProjectApp);
wxIMPLEMENT_WXWIN_MAIN_CONSOLE;
  • Build the Solution. If all goes well, the project will be built without errors.
  • Run the project, and you should see the following output.

The only small issue here is that since we have created a Windows Console project, it runs a terminal window first before running the actual application. We have to change the project type from Console to Windows. For that the following steps are required:

  • In the Solution Explorer, right click the Project item and select Properties
  • In the Properties dialog, go to Linker->System
  • In the Subsystem field, change the value to /SUBSYSTEM:WINDOWS and click Ok

Rebuild the project and now the application will run without the background console window.

If you deploy the application on some other computer, then make sure all the dll files in the execution folder are also copied along with the main exe.

В продолжение поста (новости) wxWidgets. Мелочь, но приятно, ловите печеньку.

Картинка взята с ресурса: ru.wikipedia.org, автор: Bryan Petty.

Выдержка из Wiki: wxWidgets — это кросс-платформенная библиотека инструментов с открытым исходным кодом для разработки кроссплатформенных на уровне исходного кода приложений, в частности для построения графического интерфейса пользователя (GUI).

Библиотека имеет набор классов для работы с графическими изображениями, HTML, XML документами, архивами, файловыми системами, процессами, подсистемами печати, мультимедиа, сетями, классы для организации многопоточности, отладки, отправки дампов и множество других инструментов.

Внимание! Под катом трафик!

Тройку лет назад заинтересовался кросс-платформенным программированием с использованием выше озаглавленной библиотеки. Каждый раз при сборке этой библиотеки возникало куча проблем. Проблемы не были связанны с тем, что библиотека имела какие-то существенные баги, а были связаны с тем, что при использовании подобных инструментов требующих компиляции (сборки), необходимо внимательно относится к сопровождающей литературе.
Если говорить понятным языком, то необходимо внимательно читать мануалы, readme-файлы, FAQ и т.д…

Хотя статей по сборке и использованию wxWidgets достаточно в сети, все равно считаю нужным поделится своим опытом, постараюсь объяснить шаги, которые приводят к положительному результату, и описать что к чему, чтобы разработчики только начинающие использовать wxWidgets в своих проектах, меньше наступали на грабли, и сразу перешли к использованию всех функциональных возможностей этой библиотеки.
И так, поехали.
Сборку библиотеки будем производить в операционной системе Windows 7 Professional x32 SP1. Что касается других OS, то могу смело заявить, что сборка wxWidgets под Ubuntu Desktop 12.04, не вызывает особых сложностей, все прекрасно собирается. Для сборки под GNU/Linux, можно воспользоваться этим мануалом.

В качестве IDE (редактора кода и автоматизации сборки), будем использовать Code::Blocks. Думаю многие уже о нем слышали, поэтому не будем вдаваться в подробности. Упомяну лишь, что C::B – достаточно мощный инструмент для написания больших приложений, и напрямую «заточен» под использование библиотеки инструментов wxWidgets, т.к. сам собран с использованием этой библиотеки.

1) Установка компилятора, средств отладки и предварительная настройка:
Средства отладки (дебагер), обычно устанавливаются по умолчанию вместе с компилятором, в случае компиляторов GCC и некоторых других, — это файл со скромным названием GDB.

FAQ: Первые грабли с которыми сталкиваются начинающие разработчики, — это неверная установка используемого для сборки библиотеки компилятора. Большинство устанавливают MinGW вместо TDM-GCC, на котором собственно и ведется разработка wxWidgets под Windows.

Ссылка: TDM-GCC это альфа сборка новых релизов gcc собранных для mingw
текущий официальный выпуск mingw включает в себя gcc 3 и более новых версий gcc раньше разработчиками mingw не выкладывалось. Поэтому один из разработчиков стал собирать новые gcc и выкладывать пакеты предназначенные для замены gcc в установленном mingw. Сейчас gcc 4.5 есть и у mingw http://sourceforge.net/downloads/mingw/MinGW/BaseSystem/GCC/Version4/ хз чем они отличаются…

Стоить отметить, что при установке MinGW, библиотека может собраться, но с очень малой вероятностью, скорее всего в конце сборки, после многоминутного ожидания, вы получите сообщение об ошибке вроде этой:
if not exist ..\..\lib\gcc_lib\mswud mkdir ..\..\lib\gcc_lib\mswud
g++ -c -o gcc_mswud\monolib_treectrl.o -g -O0 -mthreads -DHAVE_W32API_H -D__WXMSW__ -D_UNICODE -I..\..\lib\gcc_lib\mswud -I..\..\include -W -Wall -DWXBUILDING -I..\..\src\tiff\libtiff -I..\..\src\jpeg -I..\..\src\png -I..\..\src\zlib -I..\..\src\regex -I..\..\src\expat\lib -I..\..\src\stc\scintilla\include -I..\..\src\stc\scintilla\lexlib -I..\..\src\stc\scintilla\src -D__WX__ -DSCI_LEXER -DLINK_LEXERS -DwxUSE_BASE=1 -Wno-ctor-dtor-privacy -MTgcc_mswud\monolib_treectrl.o -MFgcc_mswud\monolib_treectrl.o.d -MD -MP ../../src/msw/treectrl.cpp
makefile.gcc:9395: recipe for target 'gcc_mswud\monolib_treectrl.o' failed

Переходим на официальный сайт компилятора TDM-GCC в раздел загрузки, скачиваем и устанавливаем последнюю стабильною версию соответствующую разрядности нашей операционной системы (x32 или x64). В нашем случае это: tdm-gcc-4.8.1-3.exe.
Далее стандартная процедура: запускаем мастер установки, и устанавливаем компилятор с опциями по умолчанию.

Совет: При установке каких либо программ, библиотек, распаковки пакетов и т.д., лучше всего использовать, в мастере установки программ, настройки (опции) по умолчанию. Поверьте, это вызовет намного меньше забот, и меньше плясок с бубном вокруг библиотек и программ. Это касается, библиотек, программ, и всевозможных компиляторов.

Настройка компилятора заключается в том, что необходимо добавить в системную переменную окружения Path, путь к бинарным сборкам компилятора, если этого не сделал мастер установки по умолчанию. Обычно это: C:\TDM-GCC-32\bin (если директорией установки (распаковки) был выбран корневой каталог диска C:\);

Проверка: Проверка работоспособности будет заключаться в следующих действиях: запускаем командную строку (CMD), и просто выполняем команду: mingw32-make -v соответственно видим версию сборки make — компоновщика. Должно появится чтото вроде этого:

2) Загрузка, распаковка и сборка библиотеки wxWidgets:
Переходим на официальный сайт библиотеки wxWidgets в раздел загрузки, скачиваем и распаковываем последнюю стабильною версию библиотеки для OS Windows. В нашем случае это: wxMSW-Setup-3.0.0.exe (Windows Installer).
Далее стандартная процедура: запускаем мастер распаковки, и распаковываем библиотеку с опциями по умолчанию.
Предварительная настройка компилятора заключается в том, что необходимо добавить системную переменную окружения WXWIN, которая будет содержать путь к корневому каталогу библиотеки. Обычно это: C:\wxWidgets-3.0.0 (если директорией установки (распаковки) был выбран корневой каталог диска C:\);

Собственно приступаем к сборке. Запускаем командную строку (CMD), и выполняем по порядку следующие команды (дожидаясь завершение выполнения каждой):

cd %WXWIN%\build\msw
mingw32-make -f makefile.gcc clean
mingw32-make -f makefile.gcc BUILD=debug SHARED=0 MONOLITHIC=0 UNICODE=1 WXUNIV=0
mingw32-make -f makefile.gcc BUILD=release SHARED=0 MONOLITHIC=0 UNICODE=1 WXUNIV=0

Обычно количество опций сборки не превышает указанных.
Разберем назначение указанных опций:

BUILD — сборка библиотеки в режиме: debug (отладки) или release (релизной версии приложения);
SHARED — тип сборки библиотеки: 0 — static статическая сборка, 1 — dynamic динамическая сборка соответственно;
MONOLITHIC — собрать все библиотеки в «одну»: 1 — да, 0 — нет, удобно на первых этапах знакомства с библиотекой;
UNICODE — Поддержка unicode: 1 — да, 0 -нет;
WXUNIV — собрать элементы интерфейса общими для любой OS: 1 — да, 0 — нет. (или сборка собственных элементов управления для операционных систем где эти элементы отсутствуют).

Процесс сборки будет похож на этот скриншот:

3) Загрузка, установка и настройка IDE Code::Blocks:
Переходим на официальный сайт программы Code::Blocks в раздел загрузки, скачиваем и устанавливаем последний стабильный бинарный релиз программы для OS Windows. В нашем случае это: codeblocks-13.12-setup.exe. Необходимо загружать версию без компилятора, т.к. компилятор мы установили ранее, и скорее всего он «свежее» компилятора который идет в поставке с C::B.

FAQ, Note: The codeblocks-13.12mingw-setup.exe file includes the GCC compiler and GDB debugger from TDM-GCC (version 4.7.1, 32 bit). The codeblocks-13.12mingw-setup-TDM-GCC-481.exe file includes the TDM-GCC compiler, version 4.8.1, 32 bit. While v4.7.1 is rock-solid (we use it to compile C::B), v4.8.1 is provided for convenience, there are some known bugs with this version related to the compilation of Code::Blocks itself.

IF UNSURE, USE «codeblocks-13.12mingw-setup.exe»!

Примечание: Общее время компиляции занимает в среднем порядка 30-40 минут. Да-да, библиотека не такая уж и маленькая, имеет кучу классов.

Далее стандартная процедура, запускаем мастер установки, и устанавливаем программу с опциями по умолчанию.

Настройки среды разработки сводятся к настройке компилятора по умолчанию. Обычно при первом запуске C::B сам выдаст диалог для выбора основного компилятора из всех найденных (выбираем TDM-GCC), но иногда этот диалог может не появлятся. Тогда запускаем C::B и переходим по пунктам главного меню к настройкам компилятора: Settings-->Compiler Вкладка: Toolchain executables и по анологии со скриншотом настраиваем C::B.

Проверка: Для проверки работоспособности среды разработки и проверки правильной настройки компиляторов, необходимо в C::B создать тестовый консольный проект, следующим образом:
1) Запускаем C::B (если он не запушен ранее);
2) Переходим по пунктам меню: File-->New-->Project в открывшимся диалоге (Project) выбираем Console application и нажимаем кнопку [Go];
3) Следуем подсказкам диалога предварительной настройки проекта, задаем параметры проекта (имя, расположение и т.д), нажимаем кнопку [Next] затем [Finish];
Открылся редактор кода проекта. Если нет то Выбираем пункты главного меню: View-->Manager, View-->Toolbars-->Compiler. Открываем исходный код в дереве менеджера main.cpp,

должен быть такой код:

если необходимо редактируем.

4) Выбираем пункт главного меню: Build-->Build and Run, и наблюдаем наше скомпилированное приложение:

4) Создание тестового проекта с использованием wxWidgets:
Запускаем C::B если он не был запущен, и переходим по пунктам главного меню: File-->New-->Projects из всех типов создаваемого проекта, выбираем wxWidgets project, нажимаем кнопку [Go].

В появившимся окне предварительной настройки проекта, следуем подсказкам, а именно:
1) Нажимаем кнопку [Next];

2) Выбираем тип используемой библиотеки wxWidgets 3.0.x, нажимаем кнопку [Next];

3) Задаем параметры проекта имя, путь к исходникам и т.д., нажимаем кнопку [Next];

4) Задаем авторов проекта (это можно пропустить), нажимаем кнопку [Next];
5) Выбираем дизайнер форм wxSmith (т.к. wxFormBuilder — у нас предварительно не установлен), также выбираем тип создаваемого приложения Frame Based, нажимаем кнопку [Next];

6) Очень внимательно отнесемся к локальной переменной, и вместо $(wx) зададим $(WXWIN), нажимаем кнопку [Next];

7) выбираем компилятор (обычно по умолчанию) нажимаем кнопку [Next];

8) в случае нашей сборки (статической-не монолитной), параметры следующего окна должны быть такими:

нажимаем кнопку [Next] и соглашаемся с диалогами.
9) Выбираем необходимые нам классы с которыми мы хотим работать.
В зависимости от способа сборки, статическая-динамическая, монолитная и ли нет следующего окна может не быть.

нажимаем кнопку [Finish];

Глобальные переменные проекта должны быть настроены следующим образом (Settings-->Global variables):

Настройки проекта должны выглядеть примерно так (Project-->Build options):
Окно Project build options (wx_test) [Вкладка Compiler settings - Other options]:

-pipe
-mthreads
-Winvalid-pch
-include wx_pch.h

Окно Project build options (wx_test) [Вкладка Compiler settings - Other options]:

__GNUWIN32__
__WXMSW__
wxUSE_UNICODE
WX_PRECOMP

Окно Project build options (wx_test) [Вкладка Linker settings]:

Окно Project build options (wx_test) [Вкладки Search directories - Compiler и Resource compiler]:

$(WXWIN)\include

Окно Project build options (Debug) [Вкладка Linker settings]:

Окно Project build options (Debug) [Вкладки Search directories - Compiler и Resource compiler]:

$(WXWIN)\lib\gcc_lib\mswud

Окно Project build options (Debug) [Вкладки Search directories - Linker]:

$(WXWIN)\lib\gcc_lib

Окно Project build options (Release) [Вкладка Linker settings]:

Окно Project build options (Release) [Вкладки Search directories - Compiler и Resource compiler]:

$(WXWIN)\lib\gcc_lib\mswu

Окно Project build options (Release) [Вкладки Search directories - Linker]:

$(WXWIN)\lib\gcc_lib

Далее сохраняем настройки путем нажатия кнопки [Ок] в форме настройки сборки проекта Project build options.

Скомпилируем (собирем) наше приложение (Build --> Build and run):

FAQ

FAQ:

Вопрос/Проблема:
Set system path!
Ответ/Решение:
set PATH (WXWIN):
C:\wxWidgets-2.9.4

Вопрос/Проблема:
if not exist gcc_mswud mkdir gcc_mswud
process_begin: CreateProcess(NULL, -c «if not exist gcc_mswud mkdir gcc_mswud», …) failed.
make (e=2): =х єфрхЄё эрщЄш єърчрээvщ Їрщы.
mingw32-make: [gcc_mswud] Error 2 (ignored)
if not exist ..\..\lib\gcc_lib mkdir ..\..\lib\gcc_lib
process_begin: CreateProcess(NULL, -c «if not exist ..\..\lib\gcc_lib mkdir ..\..\lib\gcc_
lib», …) failed.
make (e=2): =х єфрхЄё эрщЄш єърчрээvщ Їрщы.
mingw32-make: *** [..\..\lib\gcc_lib] Error 2
Ответ/Решение:
Run to cmd: set PATH=c:\mingw\bin

Вопрос/Проблема:
CodeBlocks wxWidgets’ location:
Ответ/Решение:
$(#wx) to $(WXWIN)

Вопрос/Проблема:
Global Variable Edition
Settings -> Compiler and Debugger -> Compiler Settings tab -> Compiler Options
Ответ/Решение:
base: C:\wxWidgets-2.9.4
include: C:\wxWidgets-2.9.4\include
lib: C:\wxWidgets-2.9.4\lib
cflags: `wx-config —cflags`
lflags: `wx-config —libs`
Other options:
`wx-config —cxxflags`
`wx-config —cflags`
`wx-config —libs`

что касается путей. вообще, если ты создашь wxWidgets проект в Code::Blocks, ты увидишь, что в настройках он вместо перечисления хедеров и библиотек указывает команды:
`wx-config —cflags` — в настройках компилятора
`wx-config —libs` — в настройках линкера
так вот: wx-config — это скрипт. если ты наберёшь эти команды в обычной консоли, то увидишь, что они генерируют целую последовательность флагов и файлов. у wx-config есть хэлп: wx-config —help. там описаны все вариации вызова этого скрипта. обрати внимание на опцию static.

На ошибки рода C:\wxWidgets-3.0.0\include\wx\platform.h|189|fatal error: wx/setup.h: No such file or directory|
Решение такое:
Projects —> Build options…
Debug (Search directories)
$(WXWIN)\lib\gcc_lib\mswud <—> $(WXWIN)\lib\gcc_dll\mswud

Бывают и неприятности. Например линовка может выдавать следующую ошибку:

rem gcc_mswudll\monodll_xh_combo.o: file not recognized: Memory exhausted
rem collect2.exe: error: ld returned 1 exit status
rem mingw32-make.exe: *** [..\..\lib\gcc_dll\wxmsw28u_gcc.dll] Error 1

Проявляется на некоторых 32 битных платформах при компоновке монолитной динамической библиотеки из-за нехватки памяти. Из-за того, что линковщик собранный для x86 архитектуры, не может использовать адреса выше 2Гб, даже на x86_64 архитектуре. Поэтому смена компилятора обычно не помогает, перепробованы MinGW4.4.1TDM, всё семейство MinGW4.6.x, а также MinGW4.7.0, хотя в сети есть информация, что собирается под TDM-GCC 4.5.2 sjlj.

Для компиляции в этом случае необходимо указать опцию компилятора -fno-keep-inline-dllexport:

mingw32-make -f makefile.gcc CXXFLAGS=»-fno-keep-inline-dllexport» BUILD=release SHARED=1 MONOLITHIC=1 UNICODE=1

Ещё можно использовать опцию —large-address-aware для линковщика(можно и для компилятора), но при этом надо настраивать ОС.

Также обойти проблему можно не используя монолитную сборку, или отказавшись от создания динамических библиотек для монолитной сборки, статические собираются без этой ошибки.

Upd:
Ошибки рода: This file requires compiler and library support for the ISO C++
2011 standart. This support is currently experimental, and the —std=c++11 or -std=gnu++11 compiler options.
This file requires compiler and library support for the…

Решаются явным указанием стандарта при сборке библиотеки (добавление опции):
CXXFLAGS=»-std=gnu++11″

Upd1: вероятно в последних релизах MinGW баги пофиксили, теперь можно смело собирать при помощи указанного компилятора, соблюдая те же (описанные) правила.

Upd2: при попытке собрать один из проектов в паке samples, может возникнуть следующая ошибка: «if not exist gcc_mswu mkdir gcc_mswu
process_begin: CreateProcess(NULL, -c „if not exist gcc_mswu mkdir gcc_mswu“, …) failed.» Фиксится путем добавления некоторых опций в запрос компилятора… «mingw32-make SHELL=CMD.exe -j4 -f makefile.gcc BUILD=release UNICODE=1 SHARED=0»

p/s.
Пост ориентирован прежде всего на начинающую аудиторию программистов, и не в коем случае не претендует на истину в последней инстанции.
В следующих постах опишу как «правильно» собрать библиотеку компьютерного зрения OpenCV.

Спасибо за внимание.

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

Как Вам пост?

70.56% Отличный туториал, давай еще!127

17.22% Давай по новой Миша, все фигня!31

12.22% Полно уже, ненужно это здесь.22

Проголосовали 180 пользователей. Воздержались 86 пользователей.

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

[править] Подготовка

Заходим на сайт wxWidgets и на странице загрузок скачиваем wxMSW (скачать wxMSW-2.8.8 )

[править] Установка

Устанавливаем wxMSW в некий каталог, который далее будем называть %wxWidgetsDir%

[править] Настройка

1. Запускаем Visual Studio

2. Выбираем меню File->Open->Project/Solution…, заходим в каталог %wxWidgetsDir%\build\msw и открываем файл wx.dsw.

3. В появившемся сообщении жмём Yes To All

4. В режиме Debug делаем Build Solution(F7)(собираем Debug версию)

5. переключаемся в Release и снова делаем Build Solution(F7)(собираем Realese версию)

6. Тестируем всё ли прошло хорошо: выбираем меню File->Open->Project/Solution…, заходим в каталог %wxWidgetsDir%\samples и открываем файл samples.dsw. В появившемся сообщении жмём Yes To All. Все остальные сообщения жмём Ok.
7. Теперь можно попробовать собрать, что-нибудь из появившегося списка, например «minimal». Если запустилось значит всё ok.

8. Перед тем, как создавать свой проект нужно указать пути к заголовочным файлам и библиотекам: выбираем меню Tools->Options… затем Projects and Solutions->VC++ Directories.

Указываем путь к заголовочным файлам:

%wxWidgetsDir%\include

%wxWidgetsDir%\include\msvc

и библиотекам:

%wxWidgetsDir%\lib\vc_lib.

9. Теперь можно попробовать создать свой проект: выбираем меню File->New->Project… и создаём пустой проект(Empty Project).

10. Добавляем в проект исходный файл и пишем минимальную wxWidgets программу. Пытаемся собрать(F7) и… получаем кучу ошибок  :)

11. Чтобы исправить это выбираем меню Project-><имя_проекта> Properties… затем Configuration

Properties->Linker->Input.

Теперь графу Additional Dependencies заполняем следующим содержимым:

rpcrt4.lib

comctl32.lib

Это надо делать каждый раз при создании нового проекта, или же использовать Property Sheet файл. (об этом можно посмотреть здесь)

Вот собственно и всё.

Обсуждение

Long I don’t write back in this site, and now I will write how to install wxwidgets. Why wxwidgets and not using like gtk/gtkmm/qt?

I choose wxwidgets because wxwidgets supports OOP concepts and cross platform gui application using c++ and wxwidgets in easy to compile on windows not like gtkmm, I always error for compiling newest gtkmm/gtk. And why not qt? I think qt is best cross platform gui too, but you must buy a license if you want using for commercial application.

Okay now first how to install wxwidgets on your Linux (example I using ubuntu 14.04). So to install wxwidgets, just open your terminal and write this code:

$ sudo apt-get install libwxgtk3.0-0 libwxgtk3.0-dev

And this is why I very like linux and open source? Because in Linux and now example ubuntu, to install more applications open source, we not must compile before, we just only install binary/dependencies from repository. Not like Windows, we have to compile the previous.
So if you are using windows, you must download mingw tools, mingw is compilers. Okay for mingw I using TDM-GCC because TDM-GCC is from default support wxwidget, you can see on their website in here http://tdm-gcc.tdragon.net/.
Okay for windows user, first you must need is:

  1. Download c++ compilers from here http://tdm-gcc.tdragon.net/download
  2. Download wxwidgets installer from here https://www.wxwidgets.org/downloads/. And choose Windows installers
  3. If right, the file look like this:

Installation wxwidgets on windows

Then now how to install wxwidgets on windows, you can follow this instruction:

  1. First install your TDM-GCC and install on C: directory like this

  2. And do the same thing on wxWidget installer

  3. And now make sure you have add tdm-gcc bin directory to environment variables (google it if you don’t know and how to add environment variables)

  4. Now open your command prompt and check if your mingw is can be used with this code:
    mingw32-make -version
    

    And you can get result like this:

    GNU Make 3.82.90
    Built for i686-pc-mingw32
    Copyright (C) 1988-2012 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.

  5. Then for compiling wxwidgets I follow instruction from here http://wiki.wxwidgets.org/Compiling_wxWidgets_with_MinGW. So from your command prompt, we must change active directory to wx folder:
    cd C:\wx\build\msw
    

    And now the first we must clean wxwidget source using this command:

    C:\wx\build\msw>mingw32-make -f makefile.gcc SHARED=1 UNICODE=1 BUILD=release clean
    

    If clean source finish, then you must compile the source using this command:

    C:\wx\build\msw>mingw32-make -f makefile.gcc SHARED=1 UNICODE=1 BUILD=release
    
  6. If right and you not get an error, you can have gcc_mswudll folder like this:

Update if you’re using visual studio 2013

If you’re install visual studio, you can’t install TDM-GCC compiler, because we can use windows c++ compiler. So after your visual studio installed, open windows explorer and go to C:\wx\build\msw and open file wx_vc12.sln and wait visual studio load this file until finish.

After that make sure the solution configurations is Debug mode if you want create static library or if you want create shared library you can use DLL debug/DLL Release:

What is the different of static and shared libraries?

And this is simple answer from me:

With static library, you can build/compile your applications to one file executable. But if you use with shared library, your applications need/must include .dll file

Look at this picture, I create application with static library and shared library.
This file is using shared library:

This file is using static library:

And for more info about static and shared library, read from this site http://stackoverflow.com or you can google it.
Okay then after you choose wat you want (static or shared), now right click the project from solutions explorer and select Build Solution or you can use key shortcut CTRL + SHIFT + B.

Wait until finish and not showing the error. If the compile is successfully you can see directory vc_lib in C:\wx\lib for if you’re compile using debug mode (static library) and vc_dll if you’re compile using DLL debug/DLL release mode.

And now we must create sample applications. Example for development editor I use codeblock. And for the next tutorial to create sample applications follow from this page https://imron02.wordpress.com/2014/08/21/example-c-gui-application-using-wxwidgets/

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как открыть виртуальную клавиатуру на windows 10 горячие клавиши
  • Иконки по центру панели задач windows 10 программа
  • Преимущества linux над windows
  • Код ошибки 7034 windows 10 как исправить
  • Приложение для web камеры windows xp