Alternative is to use extern
keyword. Include definition of constant in file main.cpp
, and external declaration in main.h
. This approach generate one extra file main.cpp
, but you have only one instance of constant over all translation units. For example, if you want to include const int year = 2016
in project.cpp
(all files in one directory):
$cat main.cpp
const int year = 2016;
$cat main.h
extern const int year;
$cat project.cpp
#include "main.h"
int main()
{
...
$gcc main.cpp project.cpp -o project -Wall -std=c++11
There is one important nuance: if you use straighforward definition const int year = 2016
in header, multiple inclusions of that file will generate error, but you can declare extern const int year
many times, and it is valid. You can read more about extern
in this question.
Files located in compiler search path can be included without write down path. In GNU/Linux, if file main.h
is located in /usr/include
, then you can include it simply by #include <main.h>
(more info here).
If you want to save main.h
file path to QT environment, here is answer to your question.