CMake构建Ogre项目加载插件失败,求插件库正确部署方法
我通过vcpkg安装Ogre库后创建了一个CMake项目,CMakeLists.txt配置如下:
cmake_minimum_required (VERSION ${PROJECT_CMAKE_VERSION}) project (dynamicmodeltester) find_package (Boost COMPONENTS program_options REQUIRED QUIET) find_package (imgui CONFIG REQUIRED) find_package (unofficial-imguizmo CONFIG REQUIRED) find_package (implot CONFIG REQUIRED) find_package (OGRE REQUIRED COMPONENTS Bites CONFIG) include_directories (${CMAKE_CURRENT_SOURCE_DIR}/../../..) include_directories (${Boost_INCLUDE_DIRS}) set (PROJECT_SRC Options/Application.cpp Options/Parser.cpp Application.cpp LoggerLoader.cpp main.cpp RepositoryLoader.cpp Viewer.cpp ) add_executable (${PROJECT_NAME} ${PROJECT_SRC} ${VERSION_SRC}) target_link_libraries ( ${PROJECT_NAME} PRIVATE imgui::imgui unofficial::imguizmo::imguizmo implot::implot OgreMain Codec_EXR OgreBites Codec_STBI ${Boost_LIBRARIES} ) target_compile_features(${PROJECT_NAME} PRIVATE ${PROJECT_CXX_STANDARD}) set_target_properties (${PROJECT_NAME} PROPERTIES #WIN32_EXECUTABLE ON MACOSX_BUNDLE ON )
项目可正常构建,但启动时Ogre抛出错误:
Ogre::InternalErrorException::InternalErrorException: Could not load dynamic library C:/Environments/vcpkg/packages/ogre_x64-windows/debug/etc/ogre/../../plugins/ogre\Plugin_DotScene. System Error: The specified module could not be found.
我能在项目build目录的C:\my\project\build\debug\vcpkg_installed\x64-windows\plugins\ogre路径下找到Debug版本插件Plugin_DotScene_d.dll,但手动复制到build目录后问题依旧。请问如何正确将插件库复制到build目录,让程序运行时能被Ogre找到?
1. 用CMake自动同步Ogre插件到输出目录
vcpkg安装的Ogre会暴露OGRE_PLUGIN_DIR_DEBUG和OGRE_PLUGIN_DIR_RELEASE两个变量,直接在CMakeLists.txt中添加复制逻辑,确保构建后插件自动同步到可执行文件所在目录:
# 按配置复制插件目录到输出路径的plugins/ogre子目录 add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory $<IF:$<CONFIG:Debug>,${OGRE_PLUGIN_DIR_DEBUG},${OGRE_PLUGIN_DIR_RELEASE}> $<TARGET_FILE_DIR:${PROJECT_NAME}>/plugins/ogre COMMENT "Copying Ogre plugins to output directory" )
这段代码会在编译完成后,根据当前构建配置(Debug/Release),把对应目录下的所有插件DLL复制到可执行文件所在目录的plugins/ogre子文件夹中。
2. 修正Ogre的插件加载路径
Ogre默认会读取ogre.cfg中的PluginFolder配置来查找插件,你可以通过两种方式调整:
- 代码中动态指定路径:在初始化Ogre Root对象前,设置插件目录为可执行文件所在路径的
plugins/ogre子目录:
#include <OgreRoot.h> #include <OgreFileSystemLayer.h> // 获取可执行文件的目录 std::string exePath = Ogre::FileSystemLayer::getSingleton().getExecutablePath(); Ogre::String pluginDir = exePath + "/plugins/ogre"; // 创建Root时指定插件日志路径,后续设置插件目录 Ogre::Root* root = new Ogre::Root("", "", pluginDir + "/Ogre.log"); root->setPluginPath(pluginDir);
- 修改ogre.cfg配置:找到程序运行时生成的
ogre.cfg文件,将PluginFolder的值改为相对路径plugins/ogre,或者插件所在的绝对路径:
PluginFolder=plugins/ogre
3. 确保Debug/Release插件名称匹配
Ogre的Debug插件带有_d后缀(比如Plugin_DotScene_d.dll),而Release版本无后缀。如果代码中硬编码了插件名称,要根据编译配置自动切换:
#if OGRE_DEBUG_MODE const Ogre::String dotScenePlugin = "Plugin_DotScene_d"; #else const Ogre::String dotScenePlugin = "Plugin_DotScene"; #endif root->loadPlugin(dotScenePlugin);
这样可以避免Debug模式下尝试加载无后缀的Release插件,导致找不到文件的问题。
内容的提问来源于stack exchange,提问作者Jepessen

