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 my CMakeLists.txt
I have a file called io_utils.h
with a ROOT_PATH
variable whose value is VALUE_ROOT_PATH
.
I want to replace that string with the value of the file's current directory. So I tried to add the following to CMakeLists.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?
Copy a file to another location and modify its contents. depending on whether VAR is set in CMake to any value not considered a false constant by the if() command. The "..." content on the line after the variable name, if any, is processed as above.
Local Variables You access a variable by using ${} , such as ${MY_VARIABLE} . 1. CMake has the concept of scope; you can access the value of the variable after you set it as long as you are in the same scope. If you leave a function or a file in a sub directory, the variable will no longer be defined.
CMAKE_CURRENT_LIST_DIR: Full directory of the listfile currently being processed. As CMake processes the listfiles in your project this variable will always be set to the directory where the listfile which is currently being processed (CMAKE_CURRENT_LIST_FILE) is located. The value has dynamic scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With