Raylib + CMake project setup
If you want to get started with creating games in C, I think that Raylib is probably the best option to start with. It is based on OpenGL, is very simple to use and has great community support.
Of course, you could use only your compiler to build your game's files manually and link them with Raylib, but scaling this can be difficult. You can also use Makefiles, in fact I am experimenting with integrating them myself. However, this guide will focus on CMake.
The template below is a modified version of the official template.
To get started, create a new directory and add the following file:
CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(yourprojectname)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${PROJECT_NAME}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${PROJECT_NAME}")
# For demonstration purposes, I use the C11 standard. You can generally use anything you want: C99, C11, C23 etc.
set(CMAKE_C_STANDARD 11 REQUIRED)
add_executable(${PROJECT_NAME})
add_subdirectory(src)
add_subdirectory(vendored/raylib)
target_link_libraries(${PROJECT_NAME} raylib)
add_custom_command(
TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/assets" "$<TARGET_FILE_DIR:${PROJECT_NAME}>/assets"
)
# Checks if OSX and links appropriate frameworks (only required on MacOS)
if (APPLE)
target_link_libraries(${PROJECT_NAME} "-framework IOKit")
target_link_libraries(${PROJECT_NAME} "-framework Cocoa")
target_link_libraries(${PROJECT_NAME} "-framework OpenGL")
ENDIF()
Next, you should create a src subdirectory. This is
where your source code will go. Now, create another
CMakeLists.txt file as follows:
src/CMakeLists.txt
file(GLOB_RECURSE SOURCE_FILES CONFIGURE_DEPENDS *.c)
file(GLOB_RECURSE HEADER_FILES CONFIGURE_DEPENDS *.h)
target_sources(${PROJECT_NAME} PRIVATE ${SOURCE_FILES} ${HEADER_FILES})
You should also create two more subdirectories:
-
assets- This is where your game's resources such as sprites, music and sounds will reside. -
vendored- This is where you will place third-party libraries.
The next steps
First, initialize a Git repository. After you do that, add Raylib as a submodule:
git submodule add https://github.com/raysan5/raylib vendored/raylib/
This will fetch Raylib from GitHub, using the latest commit. If you want to get a specific release instead, you can use the code below. I think this might be a better option in terms of stability.
set(RAYLIB_VERSION 5.5)
FetchContent_Declare(
raylib
DOWNLOAD_EXTRACT_TIMESTAMP OFF
URL https://github.com/raysan5/raylib/archive/refs/tags/${RAYLIB_VERSION}.tar.gz
FIND_PACKAGE_ARGS
)
Finally, to create the build files you can run this command in your project's root:
cmake -S . -B build/
Now that your build system works, you can move on to the more fun part - creating your program!