8

First of all, I already read How to read a CMake Variable in C++ source code, and I don't really know if it can help me.

Second, my question. Top level CMakeLists.txt says SET( MY_VAR /some/path ) and in top level source.cpp I need to achieve somehow a std::string containing /some/path/to/files naturally using MY_VAR value.

Community
  • 1
  • 1
Javier
  • 801
  • 3
  • 10
  • 24

3 Answers3

16
add_executable(myexe main.cpp)
if (MY_VAR)
    target_compile_definitions(myexe PRIVATE MY_VAR=${MY_VAR})
endif()

EDIT: Then the variable would be available in C++ code like that:

#ifdef MY_VAR
std::cout << MY_VAR << std::endl;
#endif
baziorek
  • 2,502
  • 2
  • 29
  • 43
steveire
  • 10,694
  • 1
  • 37
  • 48
13

You can use the configure_file(filename output_file) command. It replaces something like ${VARIABLE} or @VARIABLE@ in file filename with the actual value of cmake variable VARIABLE and writes the result to output_file.

So, you can write something like

// in C++ code
std::string my_var = "@MY_VAR@";

# in CMakeLists.txt
configure_file(filename.h.in filename.h)

Also, I think it is a good idea for the output file to be generated somewhere inside build directory (and its' containing directory added to include paths).

configure_file in cmake documentation

lisyarus
  • 15,025
  • 3
  • 43
  • 68
  • Oh, $Deity. Now I *know* I want to stay well clear from CMake. Thanks! – vonbrand Mar 07 '14 at 20:26
  • This almost worked. I mean, it did, but it replaced forever @VARIABLE@ with the value of VARIABLE. What if I change the value of VARIABLE? There's no more @VARIABLE@ to be replaced in next compilation. – Javier Mar 07 '14 at 20:46
  • What I ment by 'forever' is that I opened source.cpp and I saw no `@VARIABLE@`, but `/some/path` now. – Javier Mar 07 '14 at 20:50
  • @Javier: if the variable's value changes, the file will be regenerated when cmake will be called (and it is called automatically if building with cmake-generated makefiles). – lisyarus Mar 07 '14 at 20:50
  • 3
    @Javier: this command should be used to generate a real source file from a some kind of template file, and not to call it like `configure_file(source.cpp source.cpp)`. – lisyarus Mar 07 '14 at 20:52
-3

The only way to pass in values during compilation is by passing a macro. E.g., if CMake sets a macro called $(MY_VAR) (as make(1) does):

g++ -DMY_VAR=$(MY_VAR) .... xxx.cc

and xxx.cc uses MY_VAR as it wishes.

vonbrand
  • 11,412
  • 8
  • 32
  • 52