Reputation: 1
I'm creating my first GUI application with C++ using gtkmm and Glade. I had to merge various tutorials, because none I found is supporting Glade in combination with Gtk::Application and various classes. See the code below:
main.cpp
int main(int argc, char **argv)
{
std::cout << "Start" << std::endl;
auto app = Gtk::Application::create(argc,argv,"org.gtkmm.ex");
auto builder = Gtk::Builder::create();
builder->add_from_file("gui02.glade");
HelloWorld* helloworld;
std::cout << "helloworld compl." << std::endl;
app->run(*helloworld);
return 0;
}
helloworld.hpp
#include <gtkmm.h>
class HelloWorld : public Gtk::Window
{
protected:
Glib::RefPtr<Gtk::Builder> builder;
Gtk::Button *btn1;
Gtk::Label *lb1;
public:
HelloWorld(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade);
protected:
void on_button1_clicked();
};
helloworld.cpp
#include "helloworld.hpp"
using namespace std;
using namespace Gtk;
HelloWorld::HelloWorld(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
Gtk::Window(cobject), builder(refGlade)
{
builder->get_widget("label1", lb1);
builder->get_widget("button1", btn1);
btn1->signal_clicked().connect(sigc::mem_fun(*this, &HelloWorld::on_button1_clicked));
}
void HelloWorld::on_button1_clicked()
{
lb1->set_text("HW!");
}
Compiling using:
g++ main.cpp helloworld.cpp -o main `pkg-config gtkmm-3.0 --cflags --libs`
Result in the command line:
Start
helloworld compl.
Segmentation fault (core dumped)
Debugging with gdb (relevant extract, you get the full output if neccessary)
Glib::RefPtr::operator-> (this=0x7fffffffdd10) at /usr/include/glibmm-2.4/glibmm/refptr.h:260 260 return pCppObject_;
Thread 1 "main" received signal SIGSEGV, Segmentation fault.
0x00007ffff7a4799e in Gtk::Widget::signal_hide() () from /usr/lib/x86_64-linux-gnu/libgtkmm-3.0.so.1
Because I'm quite new to C++ (having some experience with C#), I'm not so used to pointers. Where is the error in this case?
Using a different code, where I create a Window* and use "app->run(*window)" works pretty fine, so the error occurs somewhere in the new app->run() and the outsourcing in class "HelloWorld".
Upvotes: 0
Views: 748
Reputation: 732
Your code crashes here app->run(*helloworld);
You try to dereference an empty pointer. That pointer does not point to an object in memory.
Do it like this:
HelloWorld* helloworld = new HelloWorld();
std::cout << "helloworld compl." << std::endl;
app->run(*helloworld);
Upvotes: 0