Simplifying CMake Projects with FetchContent for Cross-Platform UI Development
By Luke
FetchContent, introduced in CMake 3.11, simplifies the process of downloading and building dependencies. It is particularly useful for integrating libraries like wxWidgets into your project.
Here are the key steps to building CMakeLists.txt
using this approach:
- Specify the minimum CMake version required, noting that
FetchContent_MakeAvailable
needs at least CMake 3.14. - Define your project and the languages it supports.
- Include the FetchContent module and declare wxWidgets as a dependency.
- Automatically download, build, and link wxWidgets to your project.
- Create your executable and link it to wxWidgets.
cmake_minimum_required(VERSION 3.14 FATAL_ERROR)
project(wx_cmake_fetchcontent_template LANGUAGES CXX)
include(FetchContent)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(wxBUILD_SHARED OFF)
message(STATUS "Fetching wxWidgets...")
FetchContent_Declare(
wxWidgets
GIT_REPOSITORY https://github.com/wxWidgets/wxWidgets.git
GIT_SHALLOW ON
)
FetchContent_MakeAvailable(wxWidgets)
set(SRCS main.cpp)
add_executable(main WIN32 ${SRCS})
target_link_libraries(main PRIVATE wxcore wxnet)
Building Your Application
Follow these steps to build the project:
Debug
-
Create a build directory & configure the build:
cmake -S. -Bbuild
-
Build the project:
cmake --build build -j
This will create a build
directory and compile all necessary artifacts there. The main executable will be located in build/
.
Release
For release build use --config Release
on Windows:
cmake -S. -Bbuild
cmake --build build -j --config Release
Artifacts for both configurations will be generated in the build
directory.
On Mac or Linux you’ll need to maintain two build trees:
cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Debug
cmake --build build -j
cmake -S. -Bbuild-rel -DCMAKE_BUILD_TYPE=Release
cmake --build build-rel -j
This approach also works seamlessly for creating Debug versions, ensuring you can manage both configurations efficiently.
Handling High DPI Scaling
To ensure proper scaling for high DPI monitors, include the necessary info plist file on Mac and Manifest file on Windows. Check out my additional tutorials for detailed guides on these configurations.
Conclusion
This simplified CMake setup streamlines the development process across platforms and makes dependency management and application compilation much easier. The complete CMake template is available on my GitHub
Happy coding!