一.基础环境和使用的软件
- 操作系统:win11
- mingw工具集:i686-8.1.0-release-win32-sjlj
- IDE:clion
- wxWidgets头文件:wxWidgets-3.2.3-headers
- wxWidgets库文件:wxMSW-3.2.3_gcc810_ReleaseDLL
PS:
失败很多次才在网上看到, wxWidgets是挑mingw版本的.gcc用8.1,DLL就要用8.1
官网解释:
要在系统环境PATH设置mingw的路径
二.解压文件
将头文件和库文件解压到一个文件夹,目录如下:
ProjectRoot
├─dll
│ └─xxx.dll
└─include
├─msvc
│ └─wx
└─wx
├─xxx.h
三.创建main.cpp和CMakeLists.txt
main.cpp使用官方案例,代码如下:
// Start of wxWidgets "Hello World" Program
#include <wx/wx.h>
#include "windows.h"
class MyApp : public wxApp
{
public:
bool OnInit() override;
};
wxIMPLEMENT_APP(MyApp);
class MyFrame : public wxFrame
{
public:
MyFrame();
private:
void OnHello(wxCommandEvent& event);
void OnExit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
};
enum
{
ID_Hello = 1
};
bool MyApp::OnInit()
{
MyFrame *frame = new MyFrame();
frame->Show(true);
return true;
}
MyFrame::MyFrame()
: wxFrame(nullptr, wxID_ANY, "Hello World")
{
wxMenu *menuFile = new wxMenu;
menuFile->Append(ID_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!");
Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}
void MyFrame::OnExit(wxCommandEvent& event)
{
Close(true);
}
void MyFrame::OnAbout(wxCommandEvent& event)
{
wxMessageBox("This is a wxWidgets Hello World example",
"About Hello World", wxOK | wxICON_INFORMATION);
}
void MyFrame::OnHello(wxCommandEvent& event)
{
wxLogMessage("Hello world from wxWidgets!");
}
CMakeLists.txt代码如下:
cmake_minimum_required(VERSION 3.26)
project(wxWidgets_test)
include_directories(${PROJECT_SOURCE_DIR}/include)#设置头文件目录
link_directories(${PROJECT_SOURCE_DIR}/dll)#设置库文件目录
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/dll)#设置EXE生成目录
add_executable(main main.cpp)
target_link_libraries(main wxbase32u_gcc810.dll wxmsw32u_core_gcc810.dll)#链接动态库
四.解决遇到的问题
1.fatal error: wx/setup.h: No such file or directory
第一次编译时,会提示:
fatal error: wx/setup.h: No such file or directory
#include "wx/setup.h"
setup.h是对应各平台的设置文件,windows下要选对文件.
在include\wx\msw目录下,把setup.h复制到include\wx目录下即可.
2.出现大量undefined reference to....
主要是库文件没有链接对,官方案例只用链接wxmsw32u_core_gcc810.dll和wxbase32u_gcc810.dll.当然库文件所在目录也要写对