I'm trying to make an executable with CMake. This executable requires full path to file which is located in the project.
int main()
{
std::ifstream("fullpath_to_file");
//....
}
I think if CMake can replace certain symbols in source code with user specified string, there will be no need of hard-coding fullpath.
For example, if CMake can replace ${CMAKE_PROJECT_DIR}
in source code(cpp) into a cmake's variable like ${PROJECT_SOURCE_DIR}, then I would be able to write source like this.
int main()
{
std::ifstream("${CMAKE_PROJECT_DIR}/input/my_input.txt");
//....
}
Is there any way to do this?
Thanks.
A good way to expose as many CMake variables to you source files as you want is creating a configuration header to your project. First, create a template to the header, call it say config.h.in and define the symbols you want CMake to set at build time, for exemple the contents of config.h.in your case can be
#ifndef __CONFIG_H__
#define __CONFIG_H__
#define PROJECT_DIR @CMAKE_PROJECT_DIR@
#endif
then add to your CMakeLists.txt an instruction to change this configuration header and replace the value between the @'s with the value of the corresponding cmake variable. For instance, put the following in CMakeLists.txt:
include_directories(${CMAKE_BINARY_DIR})
config_file(
${CMAKE_SOURCE_DIR}/config.h.in
${CMAKE_BINARY_DIR}/config.h
)
Then CMake will create config.h with the definitions for the values you want to acces from your sources. Now all you have to do is: include config.h in your c++ sources and use the PROJECT_DIR macro as you expect.
No, CMake cannot do this directly. And you shouldn't do it, because you would have to place your source code within your build directory instead of your source directory.
The usual way - with respect to C++ and CMake - is to use a macro FOO_PATH
in your C++ code and
-DFOO_PATH=<path_to_foo>
via CMake.#cmakedefine FOO_PATH FOO_PATH
to your configure file config.h, define FOO_PATH within your CMake code, and regenerate your config.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