using static functions

I

iceman

Hi,
I have some staic functions inside a class..Say for example

In my .hh file

class example{
private:
static int a;
public:

static void fuc();
}

now in my .ccfile

static void func()
{
a=10;
}

I get the linking time error
undefined reference to example::a

Is it because static is valid only in a file?
How can I solve this error/
Cheers
 
R

Rolf Magnus

iceman said:
Hi,
I have some staic functions inside a class..Say for example

In my .hh file

class example{
private:
static int a;
public:

static void fuc();
}

This class definition is missing a semicolon.
now in my .ccfile

static void func()
{
a=10;
}

I get the linking time error
undefined reference to example::a

Is it because static is valid only in a file?

No. It's because you didn't define the member anywhere, only declare it. Add
to the implementation file:

int example::a;
 
J

Jeff Schwab

iceman said:
Hi,
I have some staic functions inside a class..Say for example

[Reformatted code]

/* .hh */
class example {
static int a;
public:
static void func();
};

/* .cc */
static void func() {
a = 10;
}

I get the linking time error
undefined reference to example::a

That would make sense, except that the compiler should be choking long
before the linker with a message about the undeclared variable a.
Is it because static is valid only in a file?
How can I solve this error/

You are justifiably confused by different uses of the keyword "static."
Inside a class, the "static" means that a class member is per-class,
i.e. shared by any and all instances of the class. Outside a class,
"static" means that a symbol has internal linkage. (This latter use is
deprecated in C++, and has largely been replaced by the use of unnamed
namespaces.) What your .cc file should look like is:

/* .cc */
int example::a;

void example::func() {
a = 10;
}

The first part allocates storage for the variable example::a. This will
make the linker happy. The second part defines the function func() as a
member of example, so that a is in scope. This will make the compiler
happy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,807
Latest member
ryef

Latest Threads

Top