Accessing global const variable from inside class function
May 19, 2016 at 12:07am UTC
How to Accessing global const variable from inside a class function?
The following example is my failed attempt.
If I remove the two "const" it works as expected.
global_class.h
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
class AClass
{
public :
void func()
{
extern const int g_ONE;
std::cout << g_ONE << std::endl; //undefined reference to `g_ONE'
}
};
global_main.cpp
1 2 3 4 5 6 7 8 9 10
#include "global_class.h"
AClass anObject;
const int g_ONE=1;
int main()
{
anObject.func();
}
compiler error:
1 2 3 4
$ g++ global_main.cpp
/tmp/cclPgitM.o: In function `AClass::func()':
global_main.cpp:(.text._ZN6AClass4funcEv[_ZN6AClass4funcEv]+0xe): undefined reference to `g_ONE'
collect2: error: ld returned 1 exit status
Thanks for taking a look.
Last edited on May 19, 2016 at 1:28am UTC
May 19, 2016 at 1:32am UTC
Those are two different constants. One is a global and the other is a local. I have no idea why the compiler allows declaring an extern local constant, or how one is supposed to define such a symbol.
Possibility 1: g_ONE is a local constant.
1 2 3 4 5 6 7 8 9 10
class AClass
{
public :
void func()
{
const int g_ONE = 1;
std::cout << g_ONE << std::endl;
}
};
Possibility 2: g_ONE is a static constant member, defined separately.
1 2 3 4 5 6 7 8 9 10 11 12 13
class AClass
{
static const int g_ONE;
public :
void func()
{
std::cout << g_ONE << std::endl;
}
};
//In source:
const int AClass::g_ONE = 1;
Possibility 3: g_ONE is a static constant member, defined immediately.
1 2 3 4 5 6 7 8 9
class AClass
{
static const int g_ONE = 1;
public :
void func()
{
std::cout << g_ONE << std::endl;
}
};
Possibility 4: g_ONE is a global constant.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
extern const int g_ONE;
class AClass
{
public :
void func()
{
std::cout << g_ONE << std::endl;
}
};
//In source:
const int g_ONE = 1;
May 19, 2016 at 1:44am UTC
Thanks helios. I use Possibility 4.
Topic archived. No new replies allowed.