Evgenii Legotckoi
Evgenii LegotckoiAug. 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.

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.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Ua

Qt - Test 001. Signals and slots

  • Result:84points,
  • Rating points4
Ua

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
ОК

Qt - Test 001. Signals and slots

  • Result:47points,
  • Rating points-6
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 9:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 11:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 5:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 4:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 8:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
f
firstlunoxodFeb. 15, 2025, 1:46 p.m.
Рисование на QGraphicsScene при зажатой кнопке мыши Подскажите, пожалуйста! Как данный класс можно дополнить, чтобы созданные объекты можно было перемещать мышкой по сцене?
Дмитрий
ДмитрийFeb. 3, 2025, 4:24 p.m.
Создание deb-пакета. Как создать ярлык на рабочем столе после установки собственного deb-пакета? Всем привет. Сделал свой deb-пакет с программой. Всё устанавливается и работает. Ставлю по пути /usr/bin/my_application. Как для пользователя при установке пакета сразу создать ярлык на раб…
NW
Nayo WaiJan. 30, 2025, 7:22 p.m.
не запускается компьютер!!! Не запускается компьютер (точнее работает блок , но сам монитор вообще жесть)В общем я ничего с интернета не скачивала в последнее время. На компе никаких левых пр…
n
nklyJan. 3, 2025, 12:52 p.m.
Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
M
MarselAug. 17, 2023, 12:26 a.m.
OAuth2.0 через VK, получение email Спасибо большое за помощь и простите за то что отнял время своей невнимательностью.

Follow us in social networks