Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to replace certain symbol to different symbol with CMake?

Tags:

c++

cmake

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.

like image 573
JaeJun LEE Avatar asked Dec 16 '15 12:12

JaeJun LEE


2 Answers

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.

like image 57
Elvis Teixeira Avatar answered Oct 16 '22 10:10

Elvis Teixeira


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

  1. pass -DFOO_PATH=<path_to_foo> via CMake.
  2. add a define #cmakedefine FOO_PATH FOO_PATH to your configure file config.h, define FOO_PATH within your CMake code, and regenerate your config.
like image 3
usr1234567 Avatar answered Oct 16 '22 09:10

usr1234567