mardi 27 septembre 2016

Global constant in C++ 11 used in std::array

I am aware of that global variable question has been asked many times here. For example, this one: Defining global constant in C++

And personally I prefer to use method 5 or 6:

5: const int GLOBAL_CONST_VAR = 0xFF;

6: extern const int GLOBAL_CONST_VAR; and in one source file const int GLOBAL_CONST_VAR = 0xFF;

My project requires a lot of constants, such as the solar constant. And some are used for std::array, for example, nvegetation_type , nrock_type.

I used to use the method 5, so only one header is used for all other source files. But the multiple definition problem arises similar to: Multiple definition and header-only libraries and here: Why aren't my include guards preventing recursive inclusion and multiple symbol definitions?

But this looks like not a problem in my Visual Studio C++ project and I have no idea why yet. I used makefile under Linux and it also compiled.

However, when I use method 6 and define array in other source header file in C++11 as

extern const int nvegetation_type ;
const std::array< double, nvegetation_type > some_variable
 = { { 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 
       0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1} };

I will receive errors like:

 error C2065: 'nvegetation_type': undeclared identifier.

I am assuming when I use header/source approach, I cannot directly cross refer global variables, at least for std::array. I read some similar links, but none has mentioned this (Maybe my search was unlucky). http://ift.tt/1ozGN26 So what is the solution?

Aucun commentaire:

Enregistrer un commentaire