Search code examples
c++cmakeclionundefined-referenceqt6

Qt6 functions are undefined


I installed Qt6 on Ubuntu using sudo apt install qt6-base-dev command. I created Clion Qt6 project and wrote simple window code:

#include <QCoreApplication>
#include <QDebug>
#include <QtWidgets/QWidget>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QWidget window;
    window.resize(320, 240);
    window.show();
    window.setWindowTitle(
            QCoreApplication::translate("toplevel", "Notepad")
    );
    return QCoreApplication::exec();
}

So, I tried to build it. And got error

/home/usr/CLionProjects/untitled/main.cpp:8:(.text+0x58): undefined reference to `QWidget::QWidget(QWidget*, QFlags<Qt::WindowType>)'
/usr/bin/ld: /home/usr/CLionProjects/untitled/main.cpp:10:(.text+0x7a): undefined reference to `QWidget::show()'
/usr/bin/ld: /home/usr/CLionProjects/untitled/main.cpp:11:(.text+0xb2): undefined reference to `QWidget::setWindowTitle(QString const&)'
/usr/bin/ld: /home/usr/CLionProjects/untitled/main.cpp:15:(.text+0xd2): undefined reference to `QWidget::~QWidget()'
/usr/bin/ld: /home/usr/CLionProjects/untitled/main.cpp:15:(.text+0x119): undefined reference to `QWidget::~QWidget()'
/usr/bin/ld: CMakeFiles/untitled.dir/main.cpp.o: в функции «QWidget::resize(int, int)»:
/usr/include/x86_64-linux-gnu/qt6/QtWidgets/qwidget.h:881:(.text._ZN7QWidget6resizeEii[_ZN7QWidget6resizeEii]+0x48): undefined reference to `QWidget::resize(QSize const&)'
collect2: error: ld returned 1 exit status

This is CMakeLists.txt:

cmake_minimum_required(VERSION 3.26)
project(untitled)

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)


find_package(Qt6 COMPONENTS
  Core
  REQUIRED)

add_executable(untitled main.cpp)
target_link_libraries(untitled
  Qt::Core
)

I got into the Qt6 files. And found, that all headers have declarations of classes, namespaces etc. But all C files have one string - #include <A>(where C file is a.c and header is A.h).

I tried to reinstall Qt6. But it didn't help. How can I fix it?


Solution

  • You need to add QWidget to your linked libraries, like so:

    CMakeLists.txt:

    find_package(Qt6 REQUIRED COMPONENTS Core Widgets)
    
    target_link_libraries(myapp
      Qt::Core
      Qt::Widgets
    )
    

    Additionally, to use QWidgets, you will need to use QApplication, not QCoreApplication, as the latter is for headless (non-GUI) applications. I suggest reading the section of Qt's CMake application guide focused on GUI applications.