Evgenii Legotckoi
Aug. 10, 2019, 4:09 a.m.

Using variables declared in CMakeLists.txt inside C ++ files

I propose to consider the option of using variables declared in the CMakeLists.txt file in C ++ code.

To begin with, what is it for? For example, you want to specify the version of the program and some other auxiliary information that is set during the assembly of the program, but at the same time you want to use this information in your C ++ code? Is it possible to do this? For example, to make it look like the image shows.


CMakeLists.txt

Adding such variables can be implemented by creating a configuration file with the extension h.in in which define directives will be defined, which will be added by constants from CMakeLists.txt in C ++. In this case, the corresponding header file will be generated.

  1. cmake_minimum_required (VERSION 3.8)
  2.  
  3. project (VariablesProject)
  4.  
  5. # Add the variables we need
  6. set (VERSION_MAJOR 0)
  7. set (VERSION_MINOR 1)
  8. set (VERSION_PATCH 0)
  9. set (SOFT_VERSION $ {VERSION_MAJOR}. $ {VERSION_MINOR}. $ {VERSION_PATCH})
  10.  
  11. # Specify the configuration file from which the header file will be generated
  12. configure_file (config.h.in config.h @ONLY)
  13.  
  14. add_executable ($ {PROJECT_NAME} main.cpp)
  15.  
  16. # add a directory with header files to see the generated file
  17. include_directories ($ {CMAKE_CURRENT_BINARY_DIR})
  18.  

config.h.in

The configuration file from which the header file config.h will be generated.

  1. #ifndef CONFIG_H_IN
  2. #define CONFIG_H_IN
  3.  
  4. #define PROJECT_NAME @ PROJECT_NAME @
  5. #define VERSION_MAJOR "@ VERSION_MAJOR @"
  6. #define VERSION_MINOR "@ VERSION_MINOR @"
  7. #define VERSION_PATCH "@ VERSION_PATCH @"
  8. #define SOFT_VERSION "@ SOFT_VERSION @"
  9.  
  10. #endif // CONFIG_H_IN

main.cpp

  1. #include <iostream>
  2.  
  3. #include "config.h" // Add an automatically generated configuration file
  4.  
  5. int main ()
  6. {
  7.     // Use variables from CMakeLists.txt
  8.     std :: cout << "project name:" << PROJECT_NAME << std :: endl;
  9.     std :: cout << "version:" << SOFT_VERSION << std :: endl;
  10.     std :: cout << "version major:" << VERSION_MAJOR << std :: endl;
  11.     std :: cout << "version minor:" << VERSION_MINOR << std :: endl;
  12.     std :: cout << "version patch:" << VERSION_PATCH << std :: endl;
  13.     return 0;
  14. }
  15.  

Program output

We get the following output in the console as a result.

  1. project name: VariablesProject
  2. version: 0.1.0
  3. version major: 0
  4. version minor: 1
  5. version patch: 0

UPD

The config.h file will be generated in the build directory, if you want to create it in the source directory, write this

  1. configure_file(config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/config.h @ONLY)

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html