1

My project use a version.h to configure the app version, lots of source files include this version.h, currently it defines the app version like:

#define VERSION 1

Every time I upgrade to a new version, I need to modify this VERSION, and because it's included by all the source files, the whole project recompiles, which takes a very long time.

So I want to split it into .h and .cpp. Then I just modify the .cpp when I update, and it only recompiles one file.

Here's what I tried:

test.cpp

#include <iostream>
using namespace std;

const static int VERSION;

// some other source code that uses the version
struct traits {
    const static int ver = VERSION; 
};

int main() {
    cout << traits::ver << endl; 

}

version.cpp

const int VERSION = 1;

Please note that I need to use it as static. But it doesn't compile, error:

error C2734: 'VERSION': 'const' object must be initialized if not 'extern'

error C2131: expression did not evaluate to a constant

note: failure was caused by non-constant arguments or reference to a non-constant symbol

note: see usage of 'VERSION'

What's the best way to define the version code?

Environment: Visual Studio 2015 update 3

aj3423
  • 2,003
  • 3
  • 32
  • 70
  • 1
    Possible duplicate of [How do I use extern to share variables between source files?](https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files) – Passer By Apr 26 '18 at 14:27
  • The dupe is what you are trying to do. In C++17 there is [inline variables](http://en.cppreference.com/w/cpp/language/inline). You should always include error messages. – Passer By Apr 26 '18 at 14:28
  • This question shows exact way how habit of have compile time constant uppercase created and why it is bad habit. – Slava Apr 26 '18 at 14:31
  • 1
    "Please note that I need to use it as static" no you do not. – Slava Apr 26 '18 at 14:33
  • You could make `version` a function and then auto-generate the cpp file (in your build system of choice) with the function just returning a constant. Then when the version changes, the header stays the same, only the cpp file changes. – Jesper Juhl Apr 26 '18 at 15:25
  • @aj3423 feel free to accept an answer – iPherian May 02 '18 at 13:18

2 Answers2

4

version.h

extern const int VERSION;

version.cpp

#include "version.h"

extern const int VERSION = 1;

test.cpp

#include "version.h"

struct traits {
    const static int ver;
};
const int traits::ver = VERSION;

wandbox

iPherian
  • 908
  • 15
  • 38
1

I'm using something similar.

My version.cpp looks like:

const int SoftwareVersion = 0xAA55A55A;

To Use the Version Number (as example in main.cpp) it looks like:

...
extern const int SoftwareVersion;
...
int main(int argc, char **args) {
  printf("Version %i\n",SoftwareVersion);
}
powerpete
  • 2,663
  • 2
  • 23
  • 49