Home > Enterprise >  CMakelist include subfolders
CMakelist include subfolders

Time:10-06

I can't figure out how to import my source files, which are in a different directory. The structure of my project looks like this:

root
- src
   - core
      App.h
      App.cpp
      CMakelist.txt
   CMakelist.txt
main.cpp
CMakelist.txt

My main CMakelist under root looks like this:

cmake_minimum_required(VERSION 3.17)
project(edu)

set(CMAKE_CXX_STANDARD 17)

## add subdirectory with source files
add_subdirectory(src)

add_executable(edu main.cpp)

My CMakelist under src looks like this:

add_subdirectory(core)

And finaly my CMakelist under core looks like this:

set(all_src
        App.h
        App.cpp
        )

target_sources(core ${all_src})

But it doesn't work, I get an error:

Cannot specify sources for target "core" which is not built by this project

How do I fix it? My project is getting quite large and it would be convenient to put all the files in different directories instead of stacking them in add_executable

Thx!

CodePudding user response:

The main issue here is that you never created a target called core. You need to either use either add_executable or add_library to create a target to add files to. You never created a target named core, so you're trying to add these files to something that doesn't exist.


What might help here is implementing Modern CMake, which is an approach to CMake looking at it more akin to a language than a tool. Here's a good beginners guide to structuring your project that should make it far easier to use CMake. If you want to separate your project into modules, I'd recommend making this it's own confined library within your project that will then be included into your main executable as a library. IF you just want to organize your source code, then try the method keeping separate src and include directories. It makes it far easier to organize and sort your code~

Here's some references for Modern CMake:

https://cliutils.gitlab.io/modern-cmake/

https://hsf-training.github.io/hsf-training-cmake-webpage/aio/index.html

https://gist.github.com/mbinna/c61dbb39bca0e4fb7d1f73b0d66a4fd1

  • Related