How do I use FetchContent safely in CMake for C++?

FetchContent is a CMake module that allows you to download and build dependencies directly from CMake scripts. This approach requires careful handling to avoid issues during the build process.
CMake, FetchContent, C++, CMakeLists, dependencies

cmake_minimum_required(VERSION 3.11)

project(MyProject)

include(FetchContent)

# Fetching a library (e.g., googletest)
FetchContent_Declare(
    googletest
    URL https://github.com/google/googletest/archive/release-1.10.0.tar.gz
)

# Make sure to include the fetched content
FetchContent_MakeAvailable(googletest)

# Now you can use the library in your target
add_executable(MyExecutable main.cpp)
target_link_libraries(MyExecutable gtest gtest_main)
    

CMake FetchContent C++ CMakeLists dependencies