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

cpp, C++, cmake

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.

cmake_minimum_required (VERSION 3.8)

project (VariablesProject)

# Add the variables we need
set (VERSION_MAJOR 0)
set (VERSION_MINOR 1)
set (VERSION_PATCH 0)
set (SOFT_VERSION $ {VERSION_MAJOR}. $ {VERSION_MINOR}. $ {VERSION_PATCH})

# Specify the configuration file from which the header file will be generated
configure_file (config.h.in config.h @ONLY)

add_executable ($ {PROJECT_NAME} main.cpp)

# add a directory with header files to see the generated file
include_directories ($ {CMAKE_CURRENT_BINARY_DIR})

config.h.in

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

#ifndef CONFIG_H_IN
#define CONFIG_H_IN

#define PROJECT_NAME @ PROJECT_NAME @
#define VERSION_MAJOR "@ VERSION_MAJOR @"
#define VERSION_MINOR "@ VERSION_MINOR @"
#define VERSION_PATCH "@ VERSION_PATCH @"
#define SOFT_VERSION "@ SOFT_VERSION @"

#endif // CONFIG_H_IN

main.cpp

#include <iostream>

#include "config.h" // Add an automatically generated configuration file

int main ()
{
    // Use variables from CMakeLists.txt
    std :: cout << "project name:" << PROJECT_NAME << std :: endl;
    std :: cout << "version:" << SOFT_VERSION << std :: endl;
    std :: cout << "version major:" << VERSION_MAJOR << std :: endl;
    std :: cout << "version minor:" << VERSION_MINOR << std :: endl;
    std :: cout << "version patch:" << VERSION_PATCH << std :: endl;
    return 0;
}

Program output

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

project name: VariablesProject
version: 0.1.0
version major: 0
version minor: 1
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

configure_file(config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/config.h @ONLY)
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
14,000.00 руб. - 40,000.00 руб.
Разработчик Qt
Annino, Moscow Oblast, Russia
5,000.00 руб. - 15,000.00 руб.
Дизайнер
Moskovskiy, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

D
Aug. 16, 2019, 11:58 a.m.
Damir

C++ - Тест 003. Условия и циклы

  • Result:92points,
  • Rating points8
D
Aug. 16, 2019, 11:46 a.m.
Damir

C++ - Test 005. Structures and Classes

  • Result:75points,
  • Rating points2
u
Aug. 14, 2019, 1:55 p.m.
unrealproro

C++ - Test 005. Structures and Classes

  • Result:83points,
  • Rating points4
Last comments
Aug. 19, 2019, 6:41 a.m.
Andrej Jankovich

это проблема дистрибутива, попробуйте установить через пакетный менеджер snap Суть проблемы: libQt5Core которая лежит в дистрибутиве требует версию glibc >= 2.25 у вас видимо …
b
Aug. 18, 2019, 5:09 a.m.
bbb116

cqtdeployer /home/aleks/CQtDeployer/bin/cqtdeployer: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by /home/aleks/CQtDeployer/lib/libQt5Core.so.5) linux mint …
D
Aug. 17, 2019, 8:04 a.m.
Damir

github ChekableTView Правой групповая смена значения при перетаскивании левой как обычно.
Aug. 16, 2019, 12:03 p.m.
Evgenij Legotskoj

Потому, что в минуте 60 секунд
Aug. 16, 2019, 11:16 a.m.
Dmitrij

а почему делитель 60000, а не 1000?
Now discuss on the forum
Aug. 21, 2019, 2:16 a.m.
nayk1982

Если Вы разрабатываете какую-то универсальную утилиту, которая вообще не привязана к логике, тогда как вариант: 1. Получить список таблиц через QSqlDatabase::tables 2. Для каждой табли…
Aug. 21, 2019, 12:31 a.m.
grig_p

Спасибо большое. Я долгое время писал на Object Pascal, привык, что там любое исключение, а не только сгенерированное самостоятельно, может быть перехвачено и обработано в блоках try. Дело …
Aug. 20, 2019, 1:10 p.m.
Mihailll

Нужно будет попробовать подставть другой тип данных, может заработае validator: IntValidator {bottom: 1; top: 99999999999}
Aug. 20, 2019, 12:37 p.m.
Aleksandr Panjushkin

Добрый день. Я бы хотел добавить, что в вашем коде можно было бы использовать слово auto и цикл for с перебором. Так код получился бы компактнее: auto map = new QMap<Qstring, QString&…
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB