This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Question --Why "undefined reference" linker error, when trying to use a static class member that is a pointer to another class?
- From: Jonathan Wakely <jwakely dot gcc at gmail dot com>
- To: "Steve Petrie, P.Eng." <apetrie at aspetrie dot net>
- Cc: GCC -- Help Mailing List <gcc-help at gcc dot gnu dot org>
- Date: Wed, 19 Oct 2016 11:48:03 +0100
- Subject: Re: Question --Why "undefined reference" linker error, when trying to use a static class member that is a pointer to another class?
- Authentication-results: sourceware.org; auth=none
- References: <45BEE9D077EB40FF84D393833388D3E2@Dell>
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.