![]() |
|
#1
|
|||
|
|||
Extern Variables and #include directiveHi all,
I would like to have clarifications as to what is the difference between using extern declaration and #include directive in the following context: I have 2 files (a.cc, b.cc with corresponding header files a.h and b.h) In a.cc, i have a declared a global variable say int a =10. To access the variable int a in b.cc, i need to preceed with the keyword extern. Otherwise, But when i included a.h in b.h file, i am able to access the same variable. So what difference does this make with extern and #include directive? Regards, S.Karthikeyan |
|
#2
|
|||
|
|||
|
You are including a.h in b.h, later say you are including a.h in a.cc and b.h in b.cc and that a.cc and b.cc are part of the same project(or program) then what you are actually doing here is, you are declaring the variable 'a' twice which your complier will not like very much and will error out.
externing a variable just tell the complier that this shared variable is actually declared somewhere in other source file. So your complier will not scream about it. Good idea (although not the best) will be to declare all the shared variable in one source file and extern it in a common header file. So that whenever the header file is included any source file all the shared variables are available in that source file. Source file main1.c CPP / C++ / C Code:
headerfile "headerfile.h" CPP / C++ / C Code:
source file adda.c CPP / C++ / C Code:
source file addb.c CPP / C++ / C Code:
source file addab.c CPP / C++ / C Code:
Then I complie it like Quote:
When I run it Quote:
Thanks, |
|
#3
|
|||
|
|||
True!!! - But this one !!Thanks a lot. It gives a lucid explanation.
But think whether this works: When it comes to Header files, let us say i have class definitions and have declared a global variable inside the headerfile.h;Obviously i am including this .h file in main1.cc Now when it comes to another file headerfile1.h, i am including the headerfile.h and i have a source file to perform some function definition i have included headerfile1.h; Now i can directly access the global variable defined in headerfile.h without the use of keyword extern. Let me know how is this possible. Thanks Quote:
|
Recent GIDBlog
Toyota - 2008 September Promotion by Nihal
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| [Tutorial] Pointers in C (Part I) | Stack Overflow | C Programming Language | 1 | 08-Apr-2005 18:35 |
| fltk-2.0 cvs | Plumb | FLTK Forum | 20 | 13-Nov-2004 07:10 |
| Apache2 config issues | monev | Apache Web Server Forum | 2 | 28-Jun-2004 06:19 |
| Can't view pages from another machine on the Intranet | aevans | Apache Web Server Forum | 9 | 14-May-2004 02:26 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The