const static linking problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Shuo Xiang

    const static linking problem

    Greetings:

    For the following code:

    class foo
    {
    ...
    private:
    static const int x=3;
    }

    void foo::bar()
    {
    int i=x;
    }

    ---

    When it is linked the linker always complains of "undefined reference to
    `foo::x'", why?

    Regards,

    Shuo
  • Andrey Tarasevich

    #2
    Re: const static linking problem

    Shuo Xiang wrote:[color=blue]
    > ...
    > For the following code:
    >
    > class foo
    > {
    > ...
    > private:
    > static const int x=3;
    > }
    >
    > void foo::bar()
    > {
    > int i=x;
    > }
    >
    > ---
    >
    > When it is linked the linker always complains of "undefined reference to
    > `foo::x'", why?
    > ...[/color]

    Because you forgot to define object 'foo::x' in your program. The
    declaration is present, but the definition is missing. Provide a
    definition and everything should compile without a problem

    class foo
    {
    ...
    private:
    static const int x = 3;
    };

    const int foo::x;

    void foo::bar()
    {
    int i = x;
    }

    Note, that the new (post TC1) version of C++ standard no longer requires
    'foo::x' to be defined for this particular code to compile. But your
    compiler seems to follow the requirements of the original C++ standard.

    --
    Best regards,
    Andrey Tarasevich
    Brainbench C and C++ Programming MVP

    Comment

    • Shuo Xiang

      #3
      Re: const static linking problem

      Andrey Tarasevich wrote:
      [color=blue]
      > Shuo Xiang wrote:[color=green]
      >> ...
      >> For the following code:
      >>
      >> class foo
      >> {
      >> ...
      >> private:
      >> static const int x=3;
      >> }
      >>
      >> void foo::bar()
      >> {
      >> int i=x;
      >> }
      >>
      >> ---
      >>
      >> When it is linked the linker always complains of "undefined reference to
      >> `foo::x'", why?
      >> ...[/color]
      >
      > Because you forgot to define object 'foo::x' in your program. The
      > declaration is present, but the definition is missing. Provide a
      > definition and everything should compile without a problem
      >
      > class foo
      > {
      > ...
      > private:
      > static const int x = 3;
      > };
      >
      > const int foo::x;
      >
      > void foo::bar()
      > {
      > int i = x;
      > }
      >
      > Note, that the new (post TC1) version of C++ standard no longer requires
      > 'foo::x' to be defined for this particular code to compile. But your
      > compiler seems to follow the requirements of the original C++ standard.
      >[/color]

      Greetings:

      Thank you! It was very helpful.

      Regards,

      Shuo


      Comment

      Working...