Connect with us

Global variables being redefined

Discussion in 'Microcontrollers, Programming and IoT' started by Horn, Jul 19, 2012.

Scroll to continue with content
  1. Horn


    Jun 4, 2012
    I am trying to create a function that will scroll some string across an LCD panel and have got it to work on a timer included in my PIC16F1937. My problem comes from my counting variables. I define them in my header file to make them global so the values will be saved after leaving my function. However when I exit the function and it returns to the file the values are redefined to the original values. I'm trying to find a trick to define them once in the header file with some starting values and from there have it skip that part in the header file. Any suggestions? A note to keep in mind, I am running low on memory on the chip.
  2. Harald Kapp

    Harald Kapp Moderator Moderator

    Nov 17, 2011
    This should not happen.
    You're coding "C", right?
    If a variable is defined globally, is rests ouside of the subroutine and should not be changed just by leaving the subroutine. Unles you define a variable with the same name within the subroutine. Then you have in fact two variables which only seemingly are the same. They have the same name but different scopes. The global variable is valid everywhere unless a local variable with the same name exists.

    Assume the name of the variable is "foo".
    you have code like

    int foo;
    void foobar()
    double foo;
    Both variable are named "foo", but the types differ. You can think of the gobla variable foo as being and the loval variable foo as foo.foobar (although that is not exactly the way the compiler works).

    Check your code.

  3. Horn


    Jun 4, 2012
    Sorry I forgot to mention that I have a single header file and multiple c files. I separated out my functions into different c files because my main got way too crowded. I am having luck calling the following in the header:

    #ifndef foo
    #define foo
    //define variables

    but my program is crashing so not sure if it is the variables or my scrolling function. Give me a few pokes at it.
  4. Horn


    Jun 4, 2012
    I had an indexing issue. The above trick works.
Ask a Question
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Electronics Point Logo
Continue to site
Quote of the day