Issue rebuilding main application after separate library build

I’m facing a problem with my CMake project involvind a shared library and a main application, where building the library separetly breaks the build process for the main application.

This is a simplified version of the project:

lib/
    inc/
        lib.h
    src/
        lib.c
    CMakeLists.txt
main/
    inc/
        main.h
    src/
        main.c
    CMakeLists.txt

I’m making the library a part of the build process with the add_subdirectory command:

# main/CMakeLists.txt

cmake_minimum_required(VERSION 3.10)

# Define the main application
project(MainApp)

# Create the main executable
add_executable(main
    src/main.c
)

# Add the lib directory
add_subdirectory(
    ${CMAKE_SOURCE_DIR}/../lib
    ${CMAKE_SOURCE_DIR}/../lib/build
)

# Link the library
target_link_libraries(main PRIVATE lib)

# Include header files
target_include_directories(main PUBLIC inc)

Problem description:

I want to be able to build both the main application and the lib separetly, but when using Unix Makefiles as the generator, I run into an issue:

  1. I build the main application:
cd main
mkdir build
cd build
cmake ..
cmake --build .
  1. Then I build the library separately
cd ../../lib/build
cmake ..
cmake --build .
  1. Then, when I try to build again the main application, I’m not able to build it, with this error showing up:
/home/mhast/repos/cmake_build_lib/lib/build/CMakeFiles/lib.dir/build.make:70: CMakeFiles/lib.dir/flags.make: No such file or directory
gmake[2]: *** No rule to make target 'CMakeFiles/lib.dir/flags.make'.  Stop.
gmake[1]: *** [CMakeFiles/Makefile2:125: /home/mhast/repos/cmake_build_lib/lib/build/CMakeFiles/lib.dir/all] Error 2
gmake: *** [Makefile:91: all] Error 2

Questions

  1. Why does rebuilding the library from its own build directory break the ability to rebuild the main application?
  2. Should I be structuring the project or configuring CMake differently to achieve this?

My goal is to be able to make independent builds for both the library and the main application while ensuring that the library’s existing build can be reused in the main application build, avoiding duplicates.