使用qtwindeploy部署后backEndTest.exe缺失DLL的原因排查求助
Let's break down the issues in your current CMake setup and fix them step by step:
1. The Biggest Issue: execute_process Runs at the Wrong Time
Your current setup uses execute_process to run windeployqt, but this command executes during CMake's configuration phase—before you even build your project. At that point, backEndTest.exe doesn't exist yet! So windeployqt has nothing to process, which means no DLLs get copied.
You need to run windeployqt after the executable is built, during the build phase. We can do this with add_custom_command tied directly to your test target.
2. Incorrect Order of find_package and add_subdirectory
You're adding the backEndTest subdirectory before finding Qt. If the subdirectory's CMakeLists.txt relies on Qt variables (like linking to Qt::Test), it won't have access to them yet. Always resolve dependencies first before adding subdirectories that use them.
3. Hardcoded Qt Path is Fragile
Your hardcoded QtBinDir works for your setup, but it will break if someone else uses a different Qt version or installation path. Use CMake's built-in Qt variables to get the windeployqt path dynamically.
Fixed CMakeLists.txt Example
Here's how to adjust your main CMakeLists.txt:
# First, find Qt dependencies so subdirectories can use them find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Test) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test) # Now add the test subdirectory (it can access Qt variables now) add_subdirectory(backEndTest) set(testBackEnd TRUE) if(WIN32 AND testBackEnd) # Get the full path to the built executable from the target get_target_property(BACKEND_TEST_EXE backEndTest LOCATION) # Dynamically find windeployqt using Qt's CMake variables # Qt${QT_VERSION_MAJOR}_DIR points to the cmake folder, so we go up 3 levels to reach bin get_filename_component(QT_BIN_DIR "${Qt${QT_VERSION_MAJOR}_DIR}/../../../bin" ABSOLUTE) set(WINDEPLOYQT_EXE "${QT_BIN_DIR}/windeployqt.exe") # Run windeployqt RIGHT AFTER the executable is built add_custom_command(TARGET backEndTest POST_BUILD COMMAND "${WINDEPLOYQT_EXE}" --compiler-runtime "${BACKEND_TEST_EXE}" COMMENT "Running windeployqt to copy required DLLs for backEndTest..." ) endif()
Additional Checks
- Make sure your
backEndTest/CMakeLists.txtcorrectly links against Qt's Test module:
Without this, windeployqt won't know to copy Qt Test-related DLLs.target_link_libraries(backEndTest PRIVATE Qt${QT_VERSION_MAJOR}::Test) - If you're still missing DLLs, open a command prompt, navigate to the folder with
backEndTest.exe, and run windeployqt manually:
Look for any error messages in the output—they'll tell you if windeployqt can't find certain files or dependencies.C:/Qt/6.2.3/mingw_64/bin/windeployqt.exe backEndTest.exe --compiler-runtime
内容的提问来源于stack exchange,提问作者CuriousPan

