Last active
December 25, 2021 13:04
-
-
Save nidefawl/8477ca21982a054e893967e6c47cfd7a to your computer and use it in GitHub Desktop.
Minimal CMake example. Compile all files in ./src/** to a binary in ./run/. Provides custom output names per built-type. Adds source-group and sets correct debugger settings for Visual Studio debugging.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required(VERSION 3.8) | |
# project name | |
set(BUILD_NAME "minimal-cmake-cpp") | |
# set VS_STARTUP_PROJECT for convenience. set before defining project. Fixes an issue I had in the past | |
set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT ${BUILD_NAME}) | |
# define a C + CXX project | |
project(${BUILD_NAME} C CXX) | |
# copy the output exectuable to APP_WORKING_DIR | |
set(APP_WORKING_DIR "./run/" CACHE PATH "output directory") | |
# convert ./run/ and ./src/ to absolute paths | |
get_filename_component(ABS_WORKING_DIR "${APP_WORKING_DIR}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}") | |
get_filename_component(ABS_SRC_DIR "./src/" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}") | |
message(STATUS "Working directory ${ABS_WORKING_DIR}") | |
message(STATUS "Source directory ${ABS_SRC_DIR}") | |
# glob all files in the source directory | |
file(GLOB_RECURSE HDR_ALL_FILES src/*.h) | |
file(GLOB_RECURSE CPP_ALL_FILES src/*.cpp) | |
file(GLOB_RECURSE C_ALL_FILES src/*.c) | |
set(ALL_SRC_FILES ${HDR_ALL_FILES} ${CPP_ALL_FILES} ${C_ALL_FILES}) | |
# generate source group tree for visual studio project | |
source_group(TREE ${ABS_SRC_DIR} PREFIX "src" FILES ${ALL_SRC_FILES}) | |
# add exectuable | |
add_executable(${BUILD_NAME} ${ALL_SRC_FILES}) | |
# define different output names per compiler and configuration | |
set_target_properties(${BUILD_NAME} PROPERTIES OUTPUT_NAME "${BUILD_NAME}-${CMAKE_CXX_COMPILER_ID}-$<LOWER_CASE:$<CONFIG>>") | |
# As per CMake docs: Add empty generator expr to avoid a configuration subdirectory on multi configs | |
set_target_properties(${BUILD_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ABS_WORKING_DIR}$<0:...>) | |
# set directory to run debug in | |
set_target_properties(${BUILD_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${ABS_WORKING_DIR}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment