20

I am learning c++ and cmake at the moment. I have my source files in the main directory where CMakeLists.txt is located. I want to store all source files in a /src directory, but i have no idea how to locate them in CMake.

My CMake File

cmake_minimum_required(VERSION 2.8)
project(game)

set(GAME_ALL_SOURCES
    main.cpp check.cpp
)

add_executable(game ${GAME_ALL_SOURCES})
target_link_libraries(game sfml-graphics sfml-window sfml-system)

Anyone a suggestion how to handle it?

best regards

jww
  • 97,681
  • 90
  • 411
  • 885
user2664310
  • 231
  • 1
  • 2
  • 4

2 Answers2

37

If you want to locate all .cpp files in the src directory, you could do

file(GLOB SOURCES src/*.cpp)

and use ${SOURCES} wherever you need to. For example:

add_executable(game ${SOURCES})
OMGtechy
  • 7,935
  • 8
  • 48
  • 83
Nafis Zaman
  • 1,505
  • 13
  • 16
  • 6
    If you need to include all files from all subdirectories, use `GLOB_RECURSE` instead of `GLOB` – ki92 Apr 14 '17 at 09:06
2

Try

set(GAME_ALL_SOURCES
src/main.cpp src/check.cpp
)
newman
  • 2,689
  • 15
  • 23
  • Mhh. This way looks not so comfortable. I look for sth like VPATH in make. I read from the "PROJECT_SOURCE_DIR" Cmake Variable, but i dont know how to use it. – user2664310 Aug 13 '13 at 16:46
  • 1
    PROJECT_SOURCE_DIR is not for that purpose. This variable is defined as the location of the last PROJECT() that cmake processed. – drescherjm Aug 14 '13 at 21:27
  • 2
    BTW. This answer what I have done for the 5+ years I have used CMake to generate all of my projects. – drescherjm Aug 14 '13 at 21:27
  • 1
    Also even if PROJECT_SOURCE_DIR was for that purpose wouldn't it be more painful to write set(GAME_ALL_SOURCES ${PROJECT_SOURCE_DIR}/main.cpp ${PROJECT_SOURCE_DIR}/check.cpp ) – drescherjm Aug 14 '13 at 21:49
  • +1 for this solution as it allows you to list and group specific files. If you are on CMake 3.12+, you can make the repeated prepending of the source dir ("_src/_") by using `list(TRANSFORM GAME_ALL_SOURCES PREPEND "src/"`) as described in [this answer](https://stackoverflow.com/a/55494263/2745495). – Gino Mempin Jun 27 '19 at 03:14