KcFnMi KcFnMi - 1 month ago 16
C++ Question

Where to put C++ constants? In a separated/shared header (main.h) file?

I use to put constants like:

const QString DATETIME_FORMAT {"yyyy-MM-dd hh:mm:ss.zzz"};


in a separate file,
main.h
. Actually I put it on a namespace like:

namespace projectx {
const QString DATETIME_FORMAT {"yyyy-MM-dd hh:mm:ss.zzz"};
}


And then, when I want to use
DATETIME_FORMAT
I have to:

#include "../../main.h"
using namespace projectx;


Depending on where the file using
main.h
is located the path
../../main.h
change. That's a little annoying.

Is this approach standart? What's the alternative?

Answer

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.

Comments