Linux Mint编译GTKmm 3.0程序遇链接未定义引用错误求助
GTKmm 3.0 HelloWorld编译链接错误解决
问题概述
在Linux Mint 21.1(Vera)环境下编译GTKmm 3.0的C++ HelloWorld示例时,编译阶段无报错,但链接阶段出现大量undefined reference错误,例如:
undefined reference to `Gtk::Window::Window(Gtk::WindowType)' undefined reference to `sigc::trackable::trackable()'
代码文件
helloworld.h
#ifndef GTKMM_EXAMPLE_HELLOWORLD_H #define GTKMM_EXAMPLE_HELLOWORLD_H #include <gtkmm/button.h> #include <gtkmm/window.h> class HelloWorld : public Gtk::Window { public: HelloWorld(); virtual ~HelloWorld(); protected: //Signal handlers: void on_button_clicked(); //Member widgets: Gtk::Button m_button; }; #endif
main.cpp
#include "helloworld.h" #include <iostream> HelloWorld::HelloWorld() : m_button("Hello World") // creates a new button with label "Hello World". { // Sets the border width of the window. set_border_width(10); // When the button receives the "clicked" signal, it will call the // on_button_clicked() method defined below. m_button.signal_clicked().connect(sigc::mem_fun(*this, &HelloWorld::on_button_clicked)); // This packs the button into the Window (a container). add(m_button); // The final step is to display this newly created widget... m_button.show(); } HelloWorld::~HelloWorld() { } void HelloWorld::on_button_clicked() { std::cout << "Hello World" << std::endl; }
编译错误信息(关键片段)
/usr/bin/ld: build/Debug/GNU-Linux/main.o: in function `HelloWorld::HelloWorld()': /home/fabio/NetBeansProjects/CppApplication_GTK/main.cpp:18: undefined reference to `Gtk::Window::Window(Gtk::WindowType)' /usr/bin/ld: /home/fabio/NetBeansProjects/CppApplication_GTK/main.cpp:18: undefined reference to `Glib::ustring::ustring(char const*)' /usr/bin/ld: build/Debug/GNU-Linux/main.o:(.data.rel.ro._ZTI10HelloWorld[_ZTI10HelloWorld]+0x10): undefined reference to `typeinfo for Gtk::Window' collect2: error: ld returned 1 exit status
已尝试的操作
- 在NetBeans IDE 20中手动添加了大量头文件目录和库目录(包含重复路径)
- 终端编译时使用
pkg-config调用gtk+-3.0和glib-2.0的参数,调整--libs和--cflags顺序,但问题未解决
解决方案
核心原因
错误根源是未链接GTKmm 3.0的C++库:
- 误用了C语言的GTK+ 3.0(
gtk+-3.0)的pkg-config参数,而非C++绑定的GTKmm 3.0(gtkmm-3.0) - 链接时库参数顺序错误,库需要放在目标文件之后
步骤1:确认安装GTKmm 3.0开发包
确保系统已安装GTKmm 3.0的开发文件:
sudo apt install libgtkmm-3.0-dev
步骤2:终端正确编译命令
分两步编译链接
# 编译生成目标文件 g++ -c main.cpp -o main.o $(pkg-config --cflags gtkmm-3.0) # 链接生成可执行文件 g++ main.o -o helloworld $(pkg-config --libs gtkmm-3.0)
一步完成编译链接
g++ main.cpp -o helloworld $(pkg-config --cflags --libs gtkmm-3.0)
步骤3:NetBeans IDE配置调整
- 打开项目属性,进入Build > C++ Compiler > Additional Options,添加:
$(pkg-config --cflags gtkmm-3.0) - 进入Build > Linker > Additional Options,添加:
$(pkg-config --libs gtkmm-3.0) - 移除手动添加的所有头文件目录和库目录,
pkg-config会自动处理依赖路径
原理说明
pkg-config --cflags gtkmm-3.0会自动返回GTKmm 3.0所需的所有头文件路径和编译选项;pkg-config --libs gtkmm-3.0会返回所有需要链接的库文件(包括GTKmm、sigc++等依赖库),确保链接器能找到所有符号。
内容的提问来源于stack exchange,提问作者Fabio
相关产品推荐
相关产品推荐

