"iCoder" <iFired@gmail.comschrieb im Newsbeitrag
news:1174744039.834746.181490@d57g2000hsg.googlegr oups.com...
Quote:
hi All,
This is my first post.. I am trying to understand how #include
works... I wrote a simple multi file project like this in C::B.
>
>
///// MyFunc.h ///////////
>
#ifndef MYFUNC_H_INCLUDED
#define MYFUNC_H_INCLUDED
>
int Val;
void PrintVal();
>
#endif // MYFUNC_H_INCLUDED
>
>
////////////// MyFunc.c ///////////////
#include <stdio.h>
>
#include "myfunc.h"
>
void PrintVal()
{
printf("%d",Val);
}
>
>
>
/////////////////// main.c //////////////////
#include <stdio.h>
#include <stdlib.h>
>
#include "myfunc.h"
>
int main()
{
Val = 30;
PrintVal();
return 0;
}
>
>
>
I "think" #include "xyz.pqr" dumbly replaces the line with contents of
file xyz.pqr.. Then it compiles and links.
With this "assumption" there should be a 'int Val' local to both
MyFunc.c and main.c. So whatever modifications i do for 'Val' should
No, you should have ended up with 2 global ints called Val and your Linker
should have warned about it.
Quote:
not be reflected in MyFunc.c and PrintVal should print garbage. To my
surprise it prints the value of 'Val' with exact value i have
modified.
Also tell me how "extern" works exactly.. For me, in the above
program, i should declare void PrintVal() as extern i suppose so that
main.c understands it properly.
extern in Val; in the header
int Val; in either of the the c files but not in both.
You should never ever define a variable in a header, only declare it there
using that extern specifier (telling the compiler: "there is an int called
Val somewhere, trust me") and make sure it is defined exaclty once in some c
file. If it is not defined, the linker will complain, if it is defined more
than once the linker may warn.
Bye, Jojo