Page 1 of 1

Linking: C++ and static variables

Posted: Fri Aug 27, 2004 1:11 pm
by IRBMe
I'm trying to use static variables with C++ in my kernel. Here's what the code looks like:

Code: Select all

class FooClass
{

  private:
        static int foo;
  public:
        static void bar (void);
};

...

void FooClass::bar (void)
{
    foo = 0;
}
The code compiles fine, but it won't link. I get the following linker error:

Code: Select all

fooclass.o(.text+0x20): In function `FooClass::bar()':
: undefined reference to `FooClass::foo'
Using objdump, I can see all my static method and the section is in "text". I can also see my static variable, but where the section name is, it says "*UND*". Using objdump -r I can see them there.

My linker script looks like this:

Code: Select all

OUTPUT_FORMAT("binary")
ENTRY(start)
SECTIONS
{
    . = 0x00100000;

    .text ALIGN (0x1000) :
    {
        *(.text)
        *(.rodata*)
    }

    .data ALIGN (0x1000) :
    {
      start_ctors = .;
      *(.ctor*)
      end_ctors = .;
      start_dtors = .;
      *(.dtor*)
      end_dtors = .;
      *(.data)
    }

    .bss ALIGN (0x1000) :
    {
        _sbss = .;
        *(COMMON)
        *(.bss)
        _ebss = .;
    }
}

Is there something I need to add to my linker script to get this to work or what?

Thanks in advance guys.

Re:Linking: C++ and static variables

Posted: Fri Aug 27, 2004 1:45 pm
by Candy
As in all forms of C++, putting a static member into a class doesn't reserve space for it (or you'd reserve space in each inclusion of the class header). It's similar to an extern variable.

To actually allocate space, put the declaration into one source file.

Code: Select all

static int class::member;
btw, not sure whether you include the static keyword here too, but this is the idea. Two chances, wanna bet one of the two solves it.

Re:Linking: C++ and static variables

Posted: Fri Aug 27, 2004 1:59 pm
by IRBMe
ah, thanks once again Candy ;)