Shop OBEX P1 Docs P2 Docs Learn Events
Scope/visibility of global variables — Parallax Forums

Scope/visibility of global variables

I ran into a rather nasty bug, today. I wrote

      acc= axis.nomVel - axis.actVel;
      if (acc > 0) // accelerate
      {
        if (acc > nomAcc) acc= nomAcc; // limit acceleration
      }

where I actually meant if (acc > axis.nomAcc) acc= axis.nomAcc;. Unfortunatelly I had a global variable "nomAcc" defined elsewhere so there was no error message from the compiler but instead simply the wrong value was used.

Now my question: Is a variable defined at the top level of a different .c file really globally visible, I mean in all .c compilation units? Say, int nomAcc; is defined in sub.c (but not in sub.h). top.c #includes sub.h. My understanding until now was that all comilation units (.c files) are compiled seperately and then the generated code is linked together. So at compile time, variables declared at the top level (outside any function) of sub.c should not be visible in top.c unless they are declared in the header sub.h.

I have to admit that I'm used to C++ and try to avoid such cases wherever possible by using classes and namespaces. However, at the P2 I don't have these features and have to stick to pure C, which BTW makes totally sense as C++ would unnecessarily bloat the code size and impair real-time performace by all those creator/destructor heap operations. But C is evil and you have to be careful...

Comments

  • Global variables are, well, global, and hence accessible throughout the program. To make them local to a file, declare them with "static" to give them file scope.

  • evanhevanh Posts: 15,187

    Yes, apply static declarations with a ladle. Use it for localising function definitions too.

  • Ah, OK, I understand. I have confused this because static has a different meaning in C++ classes. I loked it up and...

    • static in C++ classes means "this member variable is shared by all instanciations of the class", e.g. there is only one variable no matter how many class instances are created.
    • static for global variables in C means "this variable is not visible outside the scope of this file".
  • RossHRossH Posts: 5,345

    @ManAtWork said:
    Ah, OK, I understand. I have confused this because static has a different meaning in C++ classes. I loked it up and...

    • static in C++ classes means "this member variable is shared by all instanciations of the class", e.g. there is only one variable no matter how many class instances are created.
    • static for global variables in C means "this variable is not visible outside the scope of this file".

    C++ is not a language. It is a virus that infects C compilers.

    Happy New Year to all Propeller heads :)

Sign In or Register to comment.