Cmake Create A Binary Of Each C++ File Within A Directory

20 Jul 2024 - Syed Muhammad Shahrukh Hussain

A CMakeLists.txt file to create a binary of each file within a directory. Each c++ source file within the directory needs to have its own main entry function.

This script gets the list of files within a directory and creates a binary executable of each c++ source file.

Project directory structure

cmake-binaries
  |-- src
  |-- include
  |-- CMakeLists.txt

Solution

cmake_minimum_required (VERSION 3.20)
project (cmake-binaries)
include_directories(include)
file( GLOB SRCS src/*.cpp)

foreach(SRC ${SRCS})
  get_filename_component(FILENAME ${SRC} NAME)
  string(REGEX MATCH "^(.*)\\.[^.]*$" dummy ${FILENAME})
  set(BIN ${CMAKE_MATCH_1})
  add_executable (${BIN} ${SRC})
  message(STATUS "SRC=${SRC}")
endforeach()

Sources