How replace string in a file with value of current directory using CMake
Solution 1
I suggest a different approach using the configure_file
cmake macro. First, you create a template file that references any variables you plan to set in cmake, then the macro substitutes the actual value in place of the variable. For example, let's say we have a template file io_utils.h.in
that looks something like this:
const char* ROOT_PATH = "${BUILD_PATH}";
In your CMakeLists.txt
, you can do something like this:
configure_file( io_utils.h.in io_utils.h )
When you run cmake
, it will use the first file as a template (io_utils.h.in
here) to generate the second file (called io_utils.h
here) with the value substituted in:
const char* ROOT_PATH = "/path/to/CMakeLists.txt";
By the way, CMake has a built-in variable that references the directory with the top-level CMakeLists.txt
called CMAKE_SOURCE_DIR
. Try replacing BUILD_PATH
above with this variable.
Solution 2
In this case it seems to be a lot easier to define a macro and let the preprocessor do the job:
add_definition(ROOT_PATH ${VALUE_ROOT_PATH})

Eder Santana
Updated on July 28, 2022Comments
-
Eder Santana 10 months
I'm trying to make another guy's research code reproducible, so that others don't have the same trouble I'm having right now. But, I'm lacking the experience with cmake for that. Here is what I could do after reading the docs:
In the same folder as myCMakeLists.txt
I have a file calledio_utils.h
with aROOT_PATH
variable whose value isVALUE_ROOT_PATH
. I want to replace that string with the value of the file's current directory. So I tried to add the following toCMakeLists.txt
:# Set ROOT_PATH in io_utils.h FIND_PATH(BUILD_PATH CMakeLists.txt . ) FILE(READ ${BUILD_PATH}io_utils.h IO_UTILS) STRING(REGEX REPLACE "VALUE_ROOT_PATH" "${BUILD_PATH}" MOD_IO_UTILS "${IO_UTILS}" ) FILE(WRITE ${BUILD_PATH}io_utils.h "${MOD_IO_UTILS}")
I tried to make and install that but it is not working, the file isn't changed. What's wrong with what I did?
-
ideasman42 about 8 yearsSince not all files are headers which you may want to search/replace, it would still be interesting to have an answer to the original question, as well as this suggested alternative.
-
ComicSansMS almost 7 yearsThis has the disadvantage that the file becomes dependent on the define from the build environment. For instance, a header in a library that you want to ship to clients probably should be self-contained and not have such a dependency. But if that is of no concern, this is a valid solution.