As it stands, you've declared a global variable gval
in the header, and you've hidden that global declaration with a locally defined variable gval
in the main()
function. This is legal, but only sometimes (I'm tempted to say 'occasionally' or 'seldom') what is intended. If you use GCC, using the -Wshadow
option would warn you about shadowing variables like that. It is generally a bad idea to shadow global variables.
The simplest fix to your code is to move the definition of gval
outside main()
:
#include <stdio.h>
#include "globals.h"
int gval = 4;
int main(void)
{
printf("1st value is: %i", gval);
printf("2nd value is: %i", modded());
return 0;
}
However, you should note that although it will compile and run, the second value printed will be the same as the first because modded()
returns the unmodified version of the value. To see the effect, you need:
#include "globals.h"
int modded(void)
{
return ++gval;
}
Were it my code, there'd be a declaration of modded()
in globals.h
. You should not be calling a function without a prototype in scope according to C99 and C11 (the old and current C standard). Of necessity, the original C89 standard was more lax about that rule; it had to be to accommodate the pre-existing non-standard code. However, for code written in the 21st Century, there's no real excuse for not having a prototype in scope before you use a function.