0

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?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 1
    Put them wherever they are needed. Don't expose them where they are not. – DeiDei Oct 30 '16 at 21:51
  • 2
    Namespace-scoped `const` objects are `static` by default, so that will put a separate object in each TU that includes your header (which may or may not then be optimized into a single object by the linker). **_Not_** ideal. – ildjarn Oct 30 '16 at 21:53
  • What's the meaning of TU? – KcFnMi Oct 30 '16 at 21:54
  • With the given use cases for constant, it seems that constexpr would be a better fit (in c++11 and later) than const and static. – call me Steve Oct 30 '16 at 22:17
  • use -I option in your compiler to avoid "../../etc". `projectx::DATETIME_FORMAT` no need using namespace – Stargateur Oct 30 '16 at 22:29
  • Could you please customize the answer for usage in Qt Creator? – KcFnMi Oct 30 '16 at 22:34

1 Answers1

1

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.

Community
  • 1
  • 1
Przemek
  • 240
  • 2
  • 8