Usage of target_sources() does not work

Hello all,

I am new to cmake and therefore sorry in advance if I missed the solution to my problem in this forum.

Like many people, I have a project consisting of sub-directories with C files. I read that add_subdirectory ( <sub_dir> ) combined with target_sources ( file_list ) is the appropriate choise.

My problem is that I cannot use target_sources in the sub-dir’s CMakeLists.txt without getting

CMake Error at sub_dir/CMakeLists.txt:3 (target_sources):
  Cannot specify sources for target "mylib" which is not built by this project.

CMakeList.txt in root

cmake_minimum_required(VERSION 3.25.3 )
project( test )
include_directories (  some_dir )
add_subdirectory ( subdir )
add_library( mylib root.c dummy.c )

CMakeList.txt in sub_dir

target_sources(mylib PRIVATE some_file.c )

My CMake is a 3.25.3 on Cygwin. Once I succeed I intend to move to SOLARIS.

What am I missing ?


The call of add_library( mylib ... needs to occur before add_subdirectory. You can only call target_sources after the associated target has been created.

Hello Rob,

thanks for reply.

I figured out that my target name has to be equal to the project name for cmake to work (which is quite puzzling me).
My project is an application which runs on two linked embedded computers (redundancy) in parallel with slight differences in IO structure. My thought was having a project name and two targets, one for computer A and one for computer B. The common part can as well be a library, but for the hardware specific part the plan was to link common lib with specific files and main() - containing file.

Having Project and target name tied together is not working for me.

Can some briefly describe how I could have one project, two targets (i.e.) executables?


cmake_minimum_required(VERSION 3.20)

add_library(shared_bits SHARED)
target_sources(shared_bits PRIVATE s.cpp)

target_sources(first PRIVATE main.cpp)
target_link_libraries(first PRIVATE shared_bits)

target_sources(second PRIVATE another_main.cpp)
target_link_libraries(second PRIVATE shared_bits)

Thanks, helped a lot …