View previous topic :: View next topic |
Author |
Message |
berel
Joined: 20 Oct 2011 Posts: 15
|
Global variable unchanged in main() |
Posted: Tue Feb 09, 2021 10:00 am |
|
|
I am running PCH 5.101, Linux version.
A variable is declared in an include file before main() and hence a global variable.
When modifying the variable in a function being in the same .c file, it does not have a changed value in the main function after return from the function.
Even when adding an 'extern' the same happens.
I expected that the variable has the same value in main(), or more general, a variable has the same value in main() and functions. |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9221 Location: Greensville,Ontario
|
|
Posted: Tue Feb 09, 2021 10:46 am |
|
|
You should post a small program that this happens to as 'something' isn't right.
Off chance do you have #CASE in your program ?? |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19499
|
|
Posted: Tue Feb 09, 2021 10:52 am |
|
|
Being in an include file doesn't automatically make it global. The include file
might have a function definition around the variable, in which case
it'd be local to that function.
Look at the symbol table (Symbols from the compile menu in the IDE).
If it is global, the symbol name will be shown as an entry with nothing
else in front of it except the memory address. If instead you have the name
as something like xxxx.variable, then it is declared inside a function not
globally.
The same search would show the other possibility that there is actually a
second variable declared inside something else.
What is the variable name?. |
|
|
berel
Joined: 20 Oct 2011 Posts: 15
|
|
Posted: Wed Feb 10, 2021 10:19 am |
|
|
Thanks for both hints.
#CASE was not used, the variable name is currentPosition which should be unique.
I wrote a small sample program with global variables (output pulses as often as the global variable value) to share it, and that worked as expected.
I then found in the previous project following Ttelmah's hint that the global variable was declared in an include file and this one was included in the main.c and another source file, hence being different variables with same name.
I know, no good idea to have a global variable in an include file, had some historic reasons and is usually not done.
Confusing thing that the project ran fine with the XC8. XC8 seems to handle 'multiple' global variables in a different way. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19499
|
|
Posted: Wed Feb 10, 2021 11:00 am |
|
|
Glad you found it.
The symbol table really is your 'friend' in finding this type of problem. |
|
|
berel
Joined: 20 Oct 2011 Posts: 15
|
|
Posted: Wed Feb 10, 2021 11:04 am |
|
|
I will do so |
|
|
|