Question --Why "undefined reference" linker error, when trying to use a static class member that is a pointer to another class?

Jonathan Wakely jwakely.gcc@gmail.com
Wed Oct 19 10:48:00 GMT 2016


On 19 October 2016 at 11:42, Steve Petrie, P.Eng. wrote:
> // Define static members in file scope.
> int sub1::sub1_int;
> int* sub1::sub1_ptr_int = &sub1::sub1_int;
> sub0 sub1::*sub1_ptr_sub0;

This line doesn't do what you think it does. You've declared
sub1_ptr_sub0 as a global variable of type sub0 sub1::* i.e. a pointer
to data member.

It should be:

sub0* sub1::sub1_ptr_sub0;

> So, my question is:
>
> Why does the program (main.cpp, testns_main.cpp) build and run OK, when line
> 32 is commented out, so there is no use of the variable (repeated here from
> line 32):
>
>   sub1Object.sub1_ptr_sub0 = NULL;
>
> that points to objects of class sub0?
>
> But when line 32 is not commented out, the build of the program fails in the
> linker step, with an "undefined reference" error:
>
> obj\Debug\testns_main.o: In function `ZN7ns_main16testns_main_funcEv':
> F:/U S R/A S P/DIGDIG/CodeBlocks
> Projects/dbxdig/dbxdig_test_ns/dbxdig_testns_main/testns_main.cpp:32:
> undefined reference to `sub1::sub1_ptr_sub0'
>
> Why ???

Because you didn't define that one.



More information about the Gcc-help mailing list