In all of the projects I've created in my college classes I've always declared the variables that will be used in multiple methods (passed by reference) in my main method and then passed as needed, allowing for the main method to be nothing more than a control for what variable goes where. I understand that this is fine, but would it be an acceptable practice to make a header with all of the variables that will be used in many methods defined as extern so that I can call the variables without having to constantly pass them by reference into methods? I was thinking this might be an acceptable practice because often I find myself having to pass a variable to a method by reference in order to then pass it to another method (using the first method as nothing more than a connector) so it can be used properly. Thanks for the input in advance!

Recommended Answers

All 4 Replies

>would it be an acceptable practice to make a header with all of the
>variables that will be used in many methods defined as extern
You're substituting one problem for another. In this case, the inconvenience of passing data around versus the nightmare of global variables in all but the simplest of programs.

As Narue said, using externs can become a real nightmare for program maintenance by either you or someone else. I recall some 20+ years ago I was hired onto a new job and someone had written a C program that was about 15-20 *.c files, each file declared several global variabls which were declared extern in each of the other files that referenced them. What a nightmare that was to figure out what was declared where -- and sometimes they were declared globally in more than one *.cpp file! Finally I moved all the globals into just one file named globals.c and all the extern statements into one *.h file named externs.h. It took a week to get all that mess straightened out.

Yeah, it occurred to me later today that the whole purpose of being able to pass variables around is to avoid the nightmare that is global variables. I guess I was thinking in terms of saving on how many total "variables" were being made but, in the long term, it probably still isn't worth the hassle. Thanks for the quick responses.

My 2 cents:
It seems the last time when I have used global variables was ~30 years ago in a huge legacy package written in Fortran 66 ;). No needs in global variables at all.
Yet another (the only ;)) the extern keyword usage in C++: extern "C" for C interfaces...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.