MESSAGE
DATE | 2010-02-13 |
FROM | Ruben Safir
|
SUBJECT | Subject: [NYLXS - HANGOUT] C++ Workshop - side discussing on C++ variable declarations
|
Date: Fri, 12 Feb 2010 11:35:23 -0500 From: Chris Knadle To: NYLUG Technical Discussion Subject: Re: [nylug-talk] C++ Workshop - side discussing on C++ variable declarations User-Agent: KMail/1.12.4 (Linux/2.6.32.7-c2d-crk6; KDE/4.3.4; x86_64; ; )
On Friday 12 February 2010 03:00:23 Chris Knadle wrote: > On Thursday 11 February 2010 19:24:44 Ruben Safir wrote: > > On Thu, Feb 11, 2010 at 07:01:11PM -0500, Ajai Khattri wrote: > > > On Thu, 11 Feb 2010, Ruben Safir wrote: > > > > Anyone have any constructive insight on this conversation I had with > > > > a friend? > > > > > > I dont see what the problem is. If you're linking to code that is > > > outside the current file you must tell the compiler that it is defined > > > EXTERNally. > > > > > > Often when your code is spread across several files, you might want to > > > refer to symbols defined in other files or other libraries, so you must > > > declare them ahead of your code. > > > > Its the idea that if you define the var (that is, not use the extern > > keyword), that it can create a problem that is bothering me and getting > > under my skin.
I've created a C++ program to illustrate, as well as to test the way I thought this worked.
//================================== //file extern_test_1.cpp
#include
using namespace std;
int global_var=0; void external_increment(void); // extern funct to increment global_var by 1
void local_increment_10(void) { global_var += 10; cout << global_var << "\t after +10 locally" << endl; }
int main(void) { for (int x=0; x<4; x++) { local_increment_10(); // global_var += 10 external_increment(); // global_var += 1 external_increment(); // global_var += 1 } cout << "ending global_var: " << global_var << endl; return 0; } //==================================
//================================== // file extern_test_2.cpp
#include
using namespace std;
extern int global_var;
void external_increment(void) { global_var += 1; cout << global_var << " \t after +1 externally" << endl; } //==================================
Compiled via the command: g++ extern_test_1.cpp extern_test_2.cpp -o extern_test
Notes: - Leaving out the 'extern' keyword in extern_test_2.cpp causes a compile error. (This is a good thing!)
- In the function prototype for external_increment() in extern_test_1.cpp I didn't add the 'extern' keyword because I wanted to demonstrate that for functions (only) the 'extern' keyword is optional in C++, but it should /should/ be added there for human readability. The compiler may be able to figure out the function is external, but I wouldn't want to have to...
- Global variables should be avoided where possible
-- Chris
--
Chris Knadle Chris.Knadle-at-coredump.us
|
|