Reputation: 1
I have an older source code, like this, in a header used from many places in my project:
const int myVar = myFunc();
What I want:
myFunc()
should be called only once in the global variable initialization phase.Now the problem is that I get this warning from the .cc
I compile:
In file included from mySource.cc:7:0:
myHeader.h:59:11: warning: ‘myVar’ defined but not used [-Wunused-variable]
const int myVar = myFunc();
^
Note, mySource.cc
really doesn't use myVar
, thus the warning is okay, but other sources yes.
I think, the best would be if I would declare myVar
only in the header, some like so:
myHeader.h:
int myVar;
mySource.cc:
int myVar = myFunc();
But in this case, I can't declare it as const. This variable should be a const. Yes, I know it will be on a writable memory page, only the c++ will see it as a constant, but this is exactly what I want.
Thus, I also want to avoid this warning. Furthermore, I think myFunc()
would be called many times, what I don't want.
How can I do this?
Upvotes: 0
Views: 56
Reputation: 62603
You will have to split definition and declaration, and define the variable in the cpp file, like following:
In .h:
extern const int myVar;
In .cpp:
const int myVar = myFunc();
In C++17, inline variable would be the way to go:
inline const int myVar = myFunc();
Upvotes: 4