在windows和linux使用wxWidgets编写程序

按照上一篇文章http://www.zoudaokou.com/index.php/archives/658安装完wxWidgets后,就可以开始wxWidgets编程之旅了。

在windows下,创建一个VC工程,然后配置工程属性,加入wx的include路径,需要注意的是,在编译时会报setup.h找不到,它在include\msvc\wx目录下,将其复制到include\wx下再编译。然后再加入wx的lib路径及所需要的lib文件wxmsw30u_html.lib wxmsw30u_core.lib wxbase30u.lib wxtiff.lib wxjpeg.lib wxpng.lib wxzlib.lib wxregexu.lib wxexpat.lib即可。

在linux下,使用make install会将include和lib都安装到usr/local目录中,在写makefile文件时需要指定它们的路径和名称,而在编译wx时会生成wx-config文件,这个文件可以用来自动指定include和lib的位置以及一些编译选项,使用wx-config –libs或wx-config –cxxflags即可。

新建一个minimal.cpp文件,内容如下:

// 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

class MyApp: public wxApp
{
public:
    virtual bool OnInit();
};

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

    wxDECLARE_EVENT_TABLE();
};

enum
{
    ID_Hello = 1
};

wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
    EVT_MENU(ID_Hello,   MyFrame::OnHello)
    EVT_MENU(wxID_EXIT,  MyFrame::OnExit)
    EVT_MENU(wxID_ABOUT, MyFrame::OnAbout)
wxEND_EVENT_TABLE()

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit()
{
    MyFrame *frame = new MyFrame( "Hello World", wxPoint(50, 50), wxSize(450, 340) );
    frame->Show( true );
    return true;
}

MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
        : wxFrame(NULL, wxID_ANY, title, pos, size)
{
    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!" );
}

void MyFrame::OnExit(wxCommandEvent& event)
{
    Close( true );
}

void MyFrame::OnAbout(wxCommandEvent& event)
{
    wxMessageBox( "This is a wxWidgets' Hello world sample",
                  "About Hello World", wxOK | wxICON_INFORMATION );
}

void MyFrame::OnHello(wxCommandEvent& event)
{
    wxLogMessage("Hello world from wxWidgets!");
}

windows直接保存编译即可,linux编写的makefile文件如下:

CXX = g++

minimal: minimal.o
	$(CXX) -o minimal minimal.o `wx-config --libs`

minimal.o: minimal.cpp
	$(CXX) `wx-config --cxxflags` -c minimal.cpp -o minimal.o

clean:
	rm -f *.o minimal

或者直接用g++语句编译:

g++ minimal.cpp `wx-config --cxxflags --libs` -o minimal

然后使用make命令编译生成minimal执行文件。

最后运行生成的文件,就能看到wxWidgets窗口了。

1

Comments are closed.