You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows10+VSCode下CMake以子目录集成SDL3_ttf的方法

Windows 10下VSCode中SDL3+CMake配置问题解决(SDL_ttf依赖Freetype找不到)

问题背景

在Windows 10系统的VSCode环境中,研究CMake与SDL3的协作机制时,参考SDL2相关教程适配SDL3,遇到SDL_ttf依赖的Freetype库无法找到的错误。需要搭建指定目录结构,同时获取可运行的CMake配置示例及说明。

原CMake配置代码

cmake_minimum_required(VERSION 3.12.0)
project(helloworld)
add_subdirectory(SDL)
add_subdirectory(SDL_ttf)

add_executable(helloworld
    main.cpp
)

target_link_libraries(helloworld
PRIVATE SDL3::SDL3)
target_link_libraries(helloworld PRIVATE 
SDL3_ttf::SDL3_ttf
)

add_custom_command(
  TARGET helloworld POST_BUILD COMMAND
  ${CMAKE_COMMAND} -E copy_if_different
    "$<TARGET_FILE:SDL3::SDL3>"
    "$<TARGET_FILE:SDL3_ttf::SDL3_ttf>" 
    "$<TARGET_FILE_DIR:helloworld>"
  VERBATIM
)

错误信息

[cmake] -- SDL3_ttf: Using system freetype library
[cmake] CMake Error at C:/Program Files/CMake/share/cmake-3.31/Modules/FindPackageHandleStandardArgs.cmake:233 (message):
[cmake]   Could NOT find Freetype (missing: FREETYPE_LIBRARY FREETYPE_INCLUDE_DIRS)
[cmake] Call Stack (most recent call first):
[cmake]   C:/Program Files/CMake/share/cmake-3.31/Modules/FindPackageHandleStandardArgs.cmake:603 (_FPHSA_FAILURE_MESSAGE)
[cmake]   C:/Program Files/CMake/share/cmake-3.31/Modules/FindFreetype.cmake:165 (find_package_handle_standard_args)
[cmake]   SDL_ttf/CMakeLists.txt:266 (find_package)

期望目录结构

├── external/
│   ├── SDL3
│   ├── SDL_image
│   └── SDL_ttf
└── src/
    ├── main
    ├── ui
    └── incl

修复后的CMake配置代码

cmake_minimum_required(VERSION 3.31)
SET(SDLTTF_VENDORED ON)

project(helloworld)
add_subdirectory(SDL EXCLUDE_FROM_ALL)
add_subdirectory(SDL_ttf EXCLUDE_FROM_ALL)
add_executable( helloworld main.cpp)
target_include_directories(helloworld PRIVATE
SDL/include
SDL_ttf/include
)
target_link_libraries(helloworld
PRIVATE SDL3::SDL3
SDL3_ttf::SDL3_ttf
Freetype::Freetype
)
add_custom_command(
  TARGET helloworld PRE_BUILD COMMAND
  ${CMAKE_COMMAND} -E copy_if_different 
  $<TARGET_FILE:SDL3::SDL3>
  $<TARGET_FILE:SDL3_ttf::SDL3_ttf>
  $<TARGET_FILE:Freetype::Freetype>
    $<TARGET_FILE_DIR:helloworld>
  VERBATIM 
)

关键修复说明

  • 启用SDL_ttf自带依赖:设置SDLTTF_VENDORED ON,让SDL_ttf使用源码包中自带的Freetype库构建,避免依赖系统中未安装的Freetype。
  • 精简子目录编译:在add_subdirectory中添加EXCLUDE_FROM_ALL,仅编译SDL和SDL_ttf的核心目标,跳过测试、示例等非必要内容。
  • 显式链接Freetype目标:启用自带依赖后,SDL_ttf会生成Freetype::Freetype目标,需将其链接到可执行文件以保证依赖完整。
  • 调整动态库复制逻辑:将自定义命令改为PRE_BUILD,并添加Freetype动态库复制,确保运行时能找到所有必需的DLL文件。
  • 适配CMake版本:将最低CMake版本提升至3.31,匹配SDL3和SDL_ttf最新的CMake配置要求。

内容的提问来源于stack exchange,提问作者El_Ten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:23:19