redeclaration of variable in different object file - VxWorks

This is a discussion on redeclaration of variable in different object file - VxWorks ; Hello, I have a variable redeclared in two different object files. As linker is not giving error , Is it possible that both of them will share same memory(with out keyword extern). Thanks. Shri...

+ Reply to Thread
Results 1 to 3 of 3

Thread: redeclaration of variable in different object file

  1. redeclaration of variable in different object file

    Hello,

    I have a variable redeclared in two different object files.

    As linker is not giving error , Is it possible that both of them will
    share same memory(with out keyword extern).

    Thanks.
    Shri

  2. Re: redeclaration of variable in different object file

    Hello,

    If these are initialized global variables the linker should give you a
    warning when you link those modules together. If these are
    uninitialized global variables (or only one of them is initialized and
    the others are not) then the linker will not warn you but will make
    all references to the variable point to only one instance, so then yes
    they all will share the same storage space (google "common symbols" to
    understand what's going on).

    Cheers,

    --
    PAD

  3. Re: redeclaration of variable in different object file

    pawar.shrikant@gmail.com wrote:
    > Hello,
    >
    > I have a variable redeclared in two different object files.
    >
    > As linker is not giving error , Is it possible that both of them will
    > share same memory(with out keyword extern).
    >

    This is a really good question. Congratulations for being suspicious
    and asking about this.

    There are two possibilities. Both are bad.

    1) You've declared the two variables 'static' in the two source files.
    This is only slightly bad if you are assuming both share a piece of
    memory. Since you had to explicitly declare them 'static', you
    probably aren't making such an assumption.

    2) There is no error because the linker has bound both names to a single
    memory ares. This is not a good thing. I recommend you initialize
    one of them and declare the other one 'extern'. Now you've made your
    intention clear - there is deliberate communication between the
    modules.

    Or perhaps you didn't intentionally name the variables the same, and
    the compiler and linker conspired to connect the names to the same
    memory location, which is the unfortunate default behavior of the C
    compiler and its linker. What you have in case 2 might be called
    "surprise coupling" because it means that you have connected some
    state information between the two modules, and there's no indication
    in the source code of the connection.

    Something needs to change, and it was really smart of your to ask about
    this.

    Regards,
    Bill


+ Reply to Thread