delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/10/22/21:53:23

From: Stefan DOT Simbuerger AT physik DOT uni-regensburg DOT de (Stefan Simbuerger t2002)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Undefined reference to static members
Date: 22 Oct 1996 07:16:12 GMT
Organization: Universitaet Regensburg
Lines: 66
Distribution: inet
Message-ID: <STEFAN.SIMBUERGER.96Oct22091612@rphs38.physik.uni-regensburg.de>
References: <326BE714 DOT 3019E999 AT mnar DOT tky DOT hut DOT fi>
NNTP-Posting-Host: rphs38.physik.uni-regensburg.de
In-reply-to: Tero Parvinen's message of Mon, 21 Oct 1996 23:11:48 +0200
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

>>>>> "T" == Tero Parvinen <tero AT mnar DOT tky DOT hut DOT fi> writes:
Tero Parvinen <tero AT mnar DOT tky DOT hut DOT fi> writes:


T> I can't get djgpp to recognize static member variables. If I do a
T> 'gcc -c file.cc' everything seems to run fine, but if I try to
T> link the object files, I get messages complaining about undefined
T> references.

You merely *declared* the static variable 'a', but did not *define* it,
i.e. you did not allocate memory for 'a'. After the class declaration
you have to add the following line:

int CTest::a;

Secondly, you forgot to append the ()'s to the test.GetA-calls in the
printf's. Therefore the starting address in memory of the GetA function
gets printed (function names are pointers), and not the value of
'CTest::a', as intended!

This code works fine with me:

#include <stdio.h>

class CTest
{
 public:
    static int a;
    static void SSetA(int p);
    void SetA(int p);
    int GetA();
};

int CTest::a;     // add definition of 'a'

void CTest::SSetA(int p)
{
    a = p;
}

void CTest::SetA(int p)
{
    a = p;
}

int CTest::GetA()
{
    return a;
}

int main(int argc, char *argv[])
{
    CTest::SSetA(1);
    
    CTest test;
    printf("%u\n", test.GetA());
    test.SetA(10);     //   ^^
    printf("%u\n", test.GetA());
                       //   ^^
    return 0;          // provides defined return value
}
--
Stefan Simbuerger            Tel: +49 941 943 2002 
Universitaet Regensburg      Fax: +49 941 943 3887
e-mail: Stefan DOT Simbuerger AT physik DOT uni-regensburg DOT de
--------------------------------------------------

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019