Linking: C++ and static variables

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
IRBMe

Linking: C++ and static variables

Post 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.
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:Linking: C++ and static variables

Post 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.
IRBMe

Re:Linking: C++ and static variables

Post by IRBMe »

ah, thanks once again Candy ;)
Post Reply