Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find source directory from build directory in cmake

I want to create a bash helper script to diff a generated file against its source. The directory structure of the output matches the source, so I should be able to find the name of the source file if I had this data:

  • The name of the generated file (This will be passed to the script)
  • CMAKE_PROJECT_SOURCE_DIR (I need to find this out)

My plan to get this is:

  • go up the directory tree searching for a CMakeCache.txt file.
  • When/if found, run CMake somehow to print out the path to the source

How do I do that? Preferably without having to configure/generate(as that introduces a bit of delay). Should I instead grep a specific file in the build folder? Which one?

like image 645
user459723 Avatar asked Sep 14 '25 10:09

user459723


2 Answers

Once you have located the CMakeCache.txt you can grep for the project source dir in it in the following way:

cat CMakeCache.txt | grep -E '.*_SOURCE_DIR:STATIC=.*' | grep -E -o '/.*'

This outputs the value of the _SOURCE_DIR variable.

like image 171
sakra Avatar answered Sep 17 '25 00:09

sakra


You can grep for home directory in CMakeCache.txt:

grep ^CMAKE_HOME_DIRECTORY CMakeCache.txt | cut -d = -f2-

My cmake version:

$ cmake --version
cmake version 3.28.1
like image 40
archie2x Avatar answered Sep 17 '25 01:09

archie2x