Visual studio отладка qt
I've installed Qt, but I'm getting errors when trying to debug C++ code from within QtCreator. I'm using Visual Studio 2017 on Windows, and it seems like the debugger that QtCreator needs (cdb.exe) is not installed. How can I configure debugging to work for 64-bit code within QtCreator when using the MSVC2017 compiler?
1 Answer 1
What I discuss here is getting QtCreator working with the Visual Studio 2017 (MSVC2017) compiler--including debugging! A default installation of MSVC2017 and Qt 5.10 will allow you to compile and run code, but you won't get debugging support by default. I will show the steps necessary to get everything installed (including debugging support) for the following reference system:
Reference System
- Windows 7 SP1 x64 (works exactly the same with Win10, also)
- Visual Studio 2017 (version 15.5.1)
- Qt 5.10.0
- Qt Creator 4.5.0 (MSVC 2015, 64-bit)
- Debugging Tools for Windows (CDB.exe), which does NOT ship with Visual Studio 2017
- via Windows 10 SDK
I've tested these steps on both Windows 10 and Windows 7 (x64) and it seems to be working. Note that the version of QtCreator that comes bundled with the Qt installer is the 32 bit version, and it won't work out of the box if you're trying to do debugging using MSVC. This is documented, but not step-by-step (see QtCreator Windows Debugging and QtCreator Debugger Engines), and not everything is in one place, so I'm going to provide simple instructions here on how to get things working for the reference system I describe above.
Prerequisites
- Windows 7 x64, or Windows 10
- Visual Studio 2017 (tested with version 15.5.1)
Assuming you have Win7/Win10 and MSVC2017 installed, let's get started!
Download Qt
- Download the file qt-opensource-windows-x86-5.10.0.exe from the Qt Official Release Archive
- Install with the option "msvc2017 64-bit" checked.
- all of the other check boxes are not necessary for the configuration described here
- select "Debugging Tools for Windows" and uncheck everything else
-
The web installer will download the selected component and create a folder called "Windows Kits."
Install these two files (the x86 version is optional):
- Windows Kits\10\WindowsSDK\Installers\X64 Debuggers And Tools-x64_en-us.msi
- Windows Kits\10\WindowsSDK\Installers\X86 Debuggers And Tools-x86_en-us.msi
Install the 64-bit STAND-ALONE installer for QtCreator
NOTE: if you install QtCreator AFTER installing the Windows debugging tools, QtCreator will automatically detect the location of the debuggers, saving you the hassle when creating the kits. If you have already installed QtCreator, don't worry, configuring the kits in QtCreator is shown below.
- this version seems to have the option to select "CDB Debugger Support" (not found when installing the full Qt package that has Qt Creator bundled in)
Configure Kits in QtCreator
In QtCreator parlance or terminology, a "Kit" is a combination of debugger + compiler + Qt version + others. (In this sense, the word "Kit" does not mean the same thing as it does for "Windows Kits" when we installed the debugger above; this is an unfortunate name collision.) Set up a "QtCreator Kit" by selecting Tools -> Options -> Build & Run. I like to start on the far right tab and work to the left, ending on "Kits." The reason for this is that all of the tabs (1,2,3) below need to be configured in order to make a complete Kit.
- Set the path to C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe and give it a name like "Window Kit 10 cdb x64".
Set up the compiler. Make sure "Microsoft Visual C++ Compiler 15.0 (amd64)" is in the list. Note that QtCreator will auto-detected these locations if you've installed things to the default paths. Add the path to the compiler if it isn't listed.
Note that for Visual Studio 2017 x64 bit, you want the "amd64" version, which is the 64-bit compiler. In case you are wondering why there are so many compilers listed--they are "cross-compilers." That means they target different architectures, so for example, the "x86_amd64" is a 32-bit process that creates a 64-bit application; you would use this version if you were developing 64-bit code on a 32-bit computer (hence the term cross-compiling). Since this tutorial assumes you're running on a 64-bit OS, use the amd64 version. (The "x86_amd64" cross-compiler will also generate 64-bit code.) When I first saw the huge list of compiler selections in QtCreator, I didn't know which one to pick. Now you know, too! See When compiling x64 code, what's the difference between "x86_amd64" and "amd64"?.
- Click Add.
- Name - Give the name of the Kit; this will be the configuration you use when compiling your application.
- Compiler - Select the "Microsoft Visual C++ Compiler 15.0 (amd64)" for C and C++.
- Debugger - Select "Windows Kit 10 cdb x64" that we configured on the "Debuggers" tab
- Qt version - Select "Qt 5.10.0 (msvc2017_64). It is important to compile with the same bit-ness as the Qt libraries that you will link against.
- Click Apply.
Verify debugging works
Let's have some fun and write a 64-bit program, and then debug it. A good test is to allocate lots of memory (typical 32-bit Windows processes are limited to 2GB, see How much memory can a 32 bit process access on a 64 bit operating system? ). Allocating, say, 32GB of RAM should be a positive indicator that we are indeed compiling a 64-bit application. Here is a screen shot of QtCreator debugging a 64-bit Windows test program:
Note that I'm using the MSVC2017 64-bit compiler and the CDB.exe debugger mentioned above.
The main debugger settings are associated with the kit you build and run your project with. To specify the debugger and compiler to use for each kit, select Tools > Options > Kits.
You need to set up the debugger only if the automatic setup fails, because the native debugger is missing (as is usually the case for the CDB debugger on Windows, which you always must install yourself) or because the installed version is not supported (for example, when your system contains no, or an outdated version of GDB and you want to use a locally installed replacement instead).
Note: If you need to change the debugger to use for an automatically detected kit, you can Clone the kit and change the parameters in the clone. Make sure to select the cloned kit for your project.
If the debugger you want to use is not automatically detected, select Tools > Options > Kits > Debuggers > Add to add it.
Note: To use the debugging tools for Windows, you must install them and add the Symbol Server provided by Microsoft to the symbol search path of the debugger. For more information, see Setting CDB Paths on Windows.
Note: To use the Free Software Foundation (FSF) version of GDB on macOS, you must sign it and modify your kit settings.
This section explains the options you have for debugging C++ code and provides installation notes for the supported native debuggers. It also applies for code in other compiled languages such as C, FORTRAN, Ada.
For more information on the debugger modes, see Launching the Debugger in Different Modes.
Supported Native Debugger Versions
Qt Creator supports native debuggers when working with compiled code. On most supported platforms, the GNU Symbolic Debugger GDB can be used. On Microsoft Windows, when using the Microsoft tool chain, the Microsoft Console Debugger CDB is needed. On macOS and Linux, the LLDB debugger can be used.
The following table summarizes the support for debugging C++ code:
Platform Compiler Native Debugger Linux GCC, ICC GDB, LLDB Unix GCC, ICC GDB macOS GCC, Clang LLDB, FSF GDB (experimental) Windows/MinGW GCC GDB Windows/MSVC Microsoft Visual C++ Compiler Debugging Tools for Windows/CDB Supported GDB Versions
Starting with version 3.1, Qt Creator requires the Python scripting extension. GDB builds without Python scripting are not supported anymore and will not work. The minimum supported version is GDB 7.5 using Python version 2.7, or 3.3, or newer.
For remote debugging using GDB and GDB server, the minimum supported version of GDB server on the target device is 7.0.
Supported CDB Versions
All versions of CDB targeting platforms supported by Qt are supported by Qt Creator.
Supported LLDB Versions
The LLDB native debugger has similar functionality to the GDB debugger. LLDB is the default debugger in Xcode on macOS for supporting C++ on the desktop. LLDB is typically used with the Clang compiler (even though you can use it with GCC, too).
On macOS you can use the LLDB version delivered with Xcode or build from source. The minimum supported version is LLDB 320.4.
On Linux, the minimum supported version is LLDB 3.8.
Installing Native Debuggers
The following sections provide information about installing native debuggers.
On Windows, use the Python-enabled GDB version that is bundled with the Qt package or comes with recent versions of MinGW. On most Linux distributions, the GDB builds shipped with the system are sufficient.
You can also build your own GDB, as instructed in Building GDB.
Builds of GDB shipped with Xcode on macOS are no longer supported.
Debugging Tools for Windows
To use the CDB debugger, you must install the Debugging tools for Windows. You can download them from Download and Install Debugging Tools for Windows as part of the Windows SDK.
Note: Visual Studio does not include the Debugging tools needed, and therefore, you must install them separately.
In addition, you must select Qt Creator CDB Debugger Support (in Qt > Tools > Qt Creator) when you install Qt or the stand-alone Qt Creator.
When manually building Qt Creator using the Microsoft Visual C++ Compiler, the build process checks for the required files in "%ProgramFiles%\Debugging Tools for Windows" .
It is highly recommended that you add the Symbol Server provided by Microsoft to the symbol search path of the debugger. The Symbol Server provides you with debugging informaton for the operating system libraries for debugging Windows applications. For more information, see Setting CDB Paths on Windows.
Debugging Tools for macOS
The Qt binary distribution contains both debug and release variants of the libraries. But you have to explicitly tell the runtime linker that you want to use the debug libraries even if your application is compiled as debug, as release is the default library.
If you use a qmake based project in Qt Creator, you can set a flag in your run configuration, in Projects mode. In the run configuration, select Use debug version of frameworks.
For more detailed information about debugging on macOS, see: Mac OS X Debugging Magic.
We recommend using the LLDB version that is delivered with the latest Xcode.
Setting up FSF GDB for macOS
To use FSF GDB on macOS, you must sign it and add it to the Qt Creator kits.
- To create a key for signing FSF GDB, select Keychain Access >Certificate Assistant >Create a Certificate:
- In the Name field, input fsfgdb to replace the existing content.
- In the Certificate Type field, select Code Signing.
- Select the Let me override defaults check box.
- Select Continue, and follow the instructions of the wizard (use the default settings), until the Specify a Location For The Certificate dialog opens.
- In the Keychain field, select System.
- Select Keychain Access >System, and locate the certificate.
- Double click the certificate to view certificate information.
- In the Trust section, select Always Trust in the When using this certificate field, and then close the dialog.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.
This article describes the debugging of executables built with the Microsoft Visual Studio compilers in Qt Creator.
Installation prerequisites
Qt Creator uses the cdb.exe command line debugger provided with the Debugging Tools for Windows package as part of the Windows SDK.
As of Microsoft Visual Studio 2012, the Windows Kit 8 is installed along with Visual Studio, but cdb.exe is not included unless you check the Debugging Tools for Windows component in the installer. The debuggers are typically located in C:\Program Files (x86)\Windows Kits\8.0\Debugger.
For the older Windows SDKs, such as Windows SDK 7.1, the Debugging Tools for Windows where shipped as a separate installer on the ISO-image of the SDKs. The debuggers are typically located in C:\Program Files (x86)\Debugging Tools for Windows or C:\Program Files\Debugging Tools for Windows .
After installation, the debugger should be autodetected and show up in the Kit configuration. If it does not (due to non-standard installation paths), please point the Debugger kit configuration dialog to the location.
The 32bit version of cdb.exe can only debug 32bit executables. The 64bit version can debug both 64bit and 32bit executables, however interrupting a 32bit executable with a 64bit debugger can result in a stacktrace of the Wow64 32bit emulation layer being displayed.
Qt Creator extends the command line debugger by loading an extension library into it (qtcreatorcdbext.dll). This library must be provided for the 32bit and 64bit version of the debugger, in the folders libs\qtcreatorcdbext64 or libs\qtcreatorcdbext32 respectively.
Debugging x64 on Windows 11 Arm64 host
The "Windows Software Development Kit - Windows 10.0.22000.194" which is the current Windows 11 SDK doesn't install on a Windows 11 Arm64 host the "c:\Program Files (x86)\Windows Kits\10\Debuggers\x64" directory, wich would host the cdb.exe needed for debugging x64 applications.
By copying the above mentioned directory from a x64 Windows 11 installation, the debugging of x64 applications would work on Windows 11 Arm64 host.
Obtaining debugging information for operating system and compiler runtime libraries
When launching debugging for the first time, you are prompted to set up a Symbol server , which adds a special entry to the symbol path of the debugger. The Symbol Server provides debugging information for operating system and compiler runtime libraries. The initial download can be time-consuming.
Tips & Tricks
When the debugger fails to launch, please verify first that you can run the application by pressing the Run button. It can happen that the target selector chooses a non-runnable target.
2nd, take a look at the Debugger Log (choose Window/Views/Debugger log ). This usually shows errors. When reporting bugs related to debugging, please always attach the log. Note: Failing to start with error 135 reported usually means that a dependent DLL cannot be found.
In order to be able to view variables, etc, a debug build is required.
Debugging can be slowed down by out-of-date .pdb files. A clean build can help. Also, incremental linking can affect debugging (check for "Unable to verify checksum of module…" in the log).
Инструкции по сборке
Убедитесь, что у вас установлены следующие приложения:
- Visual Studio 2005 или выше
- Perl
- Qt 4.7.0 или новее
Откройте консоль с окружением Qt (Visual Studio build, 32 bit) и перейдите в директорию с исходными коднами аддона.
Выполните следующие команды:
cd Qt4VS2003 createUserFiles.cmd
Это создаст пути и параметры отладки
cd ComWrappers\qmakewrapper qmake nmake cd ..devenv qtappwrapper2008.sln /useenv /Build release
Измените число в имени файла qtappwrapper2008.sln взависимости от версии VS которую вы используете. Эти файлы существуют для каждой поддерживаемой версии Visual Studio.
Это соберет внешний QRC редактор который будет запускаться в Visual Studio
Теперь мы готовы открыть главный солюшн который содержит наш аддон.
Сейчас вы можете собрать солюшн. Перед попыткой запустить ваш свежесобранный аддон, прочитайте следующий раздел
Запуск и отладка
Для запуска и отладки дев-версии Qt Visual Studio Add-in нам необходимо сначала сделать маленькую работу по настройке. Заметьте, что при этом вы можете иметь установленную стабильную версию аддона. И, как вы вскоре увидите, вы можете переключаться между ними.
Установка файла описания аддона Install the Add-in's Description File
Откроте директорию в которой храняться ваши персональные настройки Visual Studio. Это обычно что-то навроде "USERPROFILE\Documents\Visual Studio 2008". Мы прсто используем этот каталог для иллюстрации, также для простоты будем читать что репозитарий аддона находится в c:.
Выполните следующие команды:
cd "USERPROFILEStudio 2008" md Addins cd Addins copy c:4VS2003\Qt4VSAddin\Qt4VSAddin.AddIn .
Qt4VSAddin.AddIn это файл описание аддона и Visual Studio теперь может найти его. Для отличных от VS2008 версий необходимо подкорректровать этот файл.
Ваша установленная релизная версия аддона сейчас отключена и не может быть загружена в Visual Studio. Для восстановления старого состояния, измените расширение вашего Qt4VSAddin.AddIn например на Qt4VSAddin.AddIn.foo. Это гарантирует что студия его проигнорирует и загрузит оригинальные настройки.
Запуск дев-версии аддона
Теперь, когда .Addin файл лежит где положено, мы готовы попробовать запустить дев-версию аддона. Откройте файл солюшена (e.g. Qt4VSAddin2008.sln) и нажмите F5.
Запустите другой экземпляр Visual Studio. Мы будем называть его VS2 и Visual Studio Instance гдe солюшн аддона загружен VS1.
Аддон еще не загружен в VS2. Для его загрузки выберите "Tools/Add-in Manager…" установите первый чекбокс в "Qt4 Add-in Development Version" и нажмите OK. Сейчас у нас должно появиться "Qt" меню в панели меню Visual Studio, что означает что аддон установлен корректно.
Отладчик не задан
Всегда раньше все работало "из коробки". А сейчас после переустановки винды поставил qtcreator и не.Отладка не запускается: "Отладчик не задан"
Собственно, установил qt комплектом с qt.io, проект выполняется в обычном режиме, но отладку.отладчик
всем привет ) подскажите,как сделать так чтоб я в отладчике мог посмотреть как notepad читает.Отладчик
Здравствуйте. Я новичок в С ++, раньше немного Basic-ом занимался. Рассматриваю главу учебника.Если вы ничего не меняли, то при установке Qt у вас должен был поставить отладчик и компилятор MinGW.
Есть какой-то. У меня здесь:C:\Program Files (x86)\Debugging Tools for Windows (x86)\cdb.exe.
Откуда взялся не ведаю (может при установке creator?). Может и к MSVC дистрибутиву отношения не имеет (а у меня именно он установлен), но в одном из комплектов, в creator, компилятор студийный и отладчик этот. Работает. Но я creator не пользуюсь, пэтому больше информации нет.Влад Фролов, удалите его и поставьте нормальный пакет Qt Creator отдельно.
На мой взгляд, подружить Visual Studio и Qt - мазохизм.Avazart, это о чём?
Добавлено через 2 минуты
Там сторонние можно подключать. Обычно он сам ищет компиляторы и отладчики в системе, и выводит список.
Добавлено через 2 минуты
ТС, наверное, так и не ответит, где он смотрит отладчики.Спасибо всем, тему можно закрывать. Разобрался с проблемой, просто установив заного, но уже с MinGW. Так что Била в жо.
Та же проблема под виндой, но с minGw дистрибутивом от qt
дистрибутив - qt-opensource-windows-x86-mingw482_opengl-5.3.2.exe
проект на cmake - установлен cmake-3.0.2-win32-x86.exeCreator нормально собирает проект, но под отладчиком не запускает. В настройках на закладке "Отладчики" креатор правильно показывает путь C:\Qt\Qt5.3.2\Tools\mingw482_32\bin\gdb.exe, но при запуске облом.
Добавлено через 12 часов 49 минут
Пробный qt-проект нормально запускается под отладчиком, срабатывают точки останова.Ещё один путь не работает. запускаю cmake над проектом:
cmake -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=Debug
формируется каталог сборки (с подкаталогами) и файлы cmake_install.cmake, Makefile и CMakeCache.txt
После этого не получается открыть проект через файл cmake_install.cmake.
Раньше QtCreator открывал проект через файл cmake_install.cmake, сейчас этот файл воспринимается как обычный текст.Читайте также: