aj3423
aj3423

Reputation: 2611

define constant int/char* in .cpp

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

Upvotes: 1

Views: 341

Answers (2)

iPherian
iPherian

Reputation: 958

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

Upvotes: 4

powerpete
powerpete

Reputation: 3052

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);
}

Upvotes: 1

Related Questions