StackOverflow Neko
StackOverflow Neko

Reputation: 140

CMake cannot figure out header dependencies if build is out-of-source?

I've been using CMake to manage a separate small c++ project (Unix Makefile based) and decided to convert it to a more organized out-of-source build. However when it's out-of-source (by doing a cmake .. in build/), my headers are no longer dependencies for their source files. If I just cmake from the top-level, everything is fine again.

So I've made a small test version and found the same problem. I'm on an Arch Linux system by the way. Originally, my project was in the /tmp directory (intentionally) and by reading this question: Handling header files dependencies with cmake, I thought this could be the culprit because CMake might be seeing directories as system ones and hence thinking my headers are from system libraries, so I moved it to my home folder. Nothing changed. I then messed around with the paths in my CMakeLists.txt, but it didn't seem to change anything. I also tried replacing everything with absolute paths.

project/CMakeLists.txt:

cmake_minimum_required (VERSION 2.8)
project (MYTEST)

include_directories(${CMAKE_SOURCE_DIR}/include)

file(GLOB SOURCES "${CMAKE_SOURCE_DIR}/src/*.cpp")
add_executable(app ${SOURCES})

project/src/hey.cpp:

#include "hey.h"

int main()
{
  std::cout << "Heyyy" << std::endl;
  return 0;
}

project/include/hey.h:

#include <iostream>

Now if I make a new directory project/build and cmake .. from that directory then make, the project compiles. However if I change hey.h in any way and try to make again, nothing will recompile. The depend.make file is consistent with this:

# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.15

CMakeFiles/app.dir/src/hey.cpp.o: ../src/hey.cpp

But if I cmake . from the top directory project, everything goes well and the dependencies are all there:

# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.15

CMakeFiles/app.dir/src/hey.cpp.o: src/hey.cpp
CMakeFiles/app.dir/src/hey.cpp.o: include/hey.h

I have found people having similar problems, but most are edge cases and cause just one header not to be included. My actual project doesn't find any header dependencies. /: I could very easily just be using CMake horribly wrong (I'm sorta new to it), but I looked around and everyone seems to do it differently.

Upvotes: 3

Views: 1453

Answers (1)

If your build directory is a subdirectory of the source directory, then it's not really out-of-source, but a sort of hybrid. The recommended CMake approach is to do proper out-of-source builds where the source and binary directory are totally unrelated. This means they can be siblings or further removed, but neither is a descendant of the other.

Upvotes: 5

Related Questions