• C

Global variables

If there are 5 .c (source) files and a .h (header) file  all to be used in one program, and each .c file will be using int a, char *string, and Struct mystruct, how can these variables be declared in the header file so that each can be used in all 5 .c files?
Can each variable be declared in the header file using 'extern' and
can the definition for each be placed in the file which contains main(), thus
using the variables in all files?
misbellAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

fasterCommented:
yes, define global variable as extern in the include file, and in one c file, declare it actually.
0
RONSLOWCommented:
DECLARE them in your header.h (with extern) - also you'd probably delcare your struct Struct in the same header file.

  extern int a;
  extern char* string;
  extern struct Struct mystruct;

#include in EACH .c file that needs to access these globals

  #include "header.h"

DEFINE them in exactly ONE .c file (give initial values is a good idea). The definitions would appear AFTER the #include "header.h"

  int a = 0;
  char* string = NULL;
  struct Struct mystruct;

this could be your main.c, or there may be a suitable source file where these variables are maintained and managed where the definition should be.

0
RONSLOWCommented:
DECLARE them in your header.h (with extern) - also you'd probably delcare your struct Struct in the same header file.

  extern int a;
  extern char* string;
  extern struct Struct mystruct;

#include in EACH .c file that needs to access these globals

  #include "header.h"

DEFINE them in exactly ONE .c file (give initial values is a good idea). The definitions would appear AFTER the #include "header.h"

  int a = 0;
  char* string = NULL;
  struct Struct mystruct;

this could be your main.c, or there may be a suitable source file where these variables are maintained and managed where the definition should be.

0
ON-DEMAND: 10 Easy Ways to Lose a Password

Learn about the methods that hackers use to lift real, working credentials from even the most security-savvy employees in this on-demand webinar. We cover the importance of multi-factor authentication and how these solutions can better protect your business!

sgantaCommented:

Declare all your global variables in one header file
Eg.
#include <stdio.h>                   /* def.h */
int a;
char *string;
struct mystruct{
                          /* Variables */
                      };
/* End of the File */

Now you include this file in your all source files
using
#include "def.h"
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RONSLOWCommented:
sganta : that's jusy plain wrong !!

misbell . please reject this answer so my earlier (correct) comments can be put up as an answer.

I was unable to answer before as the question was still locked.

0
bertvermeerbergenCommented:
In addition to the RONSLOW answer, I'm using a little trick to make live easier:
Use following defines at the start of your (single) .h file:
#ifdef DEFINE_DATA
  #define EXTERN
  #define INIT(x)  = x
#else
  #define EXTERN extern
  #define INIT(x)
#endif

Then combine the declaration, definition and initialization of each global like this:
EXTERN int a INIT(0);
EXTERN char *string INIT(NULL);

In your 'main' .c file (and only there!), add following line before the include of .h:
#define DEFINE_DATA

This way, you will have all the code you need in a single source location, something I like very much.  Again, RONSLOW solution is 100 % correct, and in fact the above defines only simplify coding and maintenance.

For RONSLOW: I have seen (PC) linkers accepting a definition of  the same variable more than once, as long as it is done exactly the same way.  I don't like it and would not depend on it, but it can be done sometimes.
0
RONSLOWCommented:
I've seen the same .. and when a new version of the compiler/linker came out .. whammy, the code didn't build.  But that was MANY years ago (while ANSI C was in its infancy).

Also, the #define DEFINE_DATA in main.c is good for very small examples.  But for really small examples, it isn't too hard to do the defining of variables by hand anyway.

For a larger application, you really wouldn't want ALL your #include's to be put into main just so the variables get defined somewhere.  And if you spread the definitions around, you can get into trouble because you inadvertently define them in more than one place.

It is a good idea in theory (keeping a single source location) .. but you may find it cause problems because of the way C and the preprocessor work.

0
bertvermeerbergenCommented:
As usual in the C world, there are different programming 'cultures'.
I am including all the .h files in a main.c for the very reason of
defining the global data.  In fact, the only other thing my main.c
file typically contains is a main() routine to gets things started.
Everything else is contained in more specific .c modules.
For me, by definition a 'global' variable should not be owned by
any specific module and therefor the most appropriate place to
define it is in the main file.  But I know there are different point of
views about this, and the defines may not be as useful in the
other cases.
This said, I have used the defines this way in a project of over
100000 lines and dozens of files.  They never caused me any
suprises.
0
RONSLOWCommented:
AN INCORRECT ANSWER WAS ACCEPTED HERE .. the code given is WRONG !!!

misbell - why did you allow it to be accepted ?!?!?!

0
sgantaCommented:
Dear Bro. RONSLOW

Why are you thinking like that. This is 100% correct and it is easier to write.
Because we have used these types in our projects when we were writing code
for PASCAL Compiler using C Language.

Explanation: --

He wants that all the global variables are should be visible in all the source code files.

Method 1
1. Since he wants for all the files. Is it not good to define single file,
    and include this definition into all the files.
   
Method 2 (RONSLOW Method)
You are having global variables in the MAIN files
and each time you have to declare all the required global variables in the
Source Code by using EXTERN. This also works but this is not advisable
as per the software standards in some cases. Because this requires additional
code to write in the source files.

He clearly says that all the variables should be recognizable by all the 6 source files.
So, My method is correct.

Please Note that. I am not worrying about my points.
I Love JESUS. He cleanses me with HIS PRECIOUS BLOOD. Tho' I am from different
religion I have accepted JESUS CHRIST as my personal SAVIOUR.

If you want you can reject my answer. I don't mind it. Because HIS LOVE OVERFLOWS
in my HEART. I want you to know that I Love You.

                                          Thank You -- SGANTA (Sarat Kumar)  


You can also try that. I am not worrying about points


0
RONSLOWCommented:
>Dear Bro. RONSLOW

Hi Bro !!

>Why are you thinking like that. This is 100% correct and it is
>easier to write.

Easier than putting the 'extern' prefix in front, which is required ??

I guess there are few extra characters to type .. but this certainly does not increase the difficulty.

>Because we have used these types in our projects when we were
>writing code for PASCAL Compiler using C Language.

You may have a non-standard compiler that accepts this incorrect method.  For example, some older MS compilers used to accept this .. but it is NOT standard C

>Explanation: --
>
>He wants that all the global variables are should be visible in
>all the source code files.
>
>Method 1
>1. Since he wants for all the files. Is it not good to define
>single file,
>    and include this definition into all the files.

That is EXACTLY what my (and faster's) method involves also .. my main issue is that you failed to put the required 'extern' infront of the declarations.

>Method 2 (RONSLOW Method)
>You are having global variables in the MAIN files

You need to define a variable SOMEWHERE .. it cannot just exist ONLY in a .h  There needs to be a .c file that defines a global variable.

>and each time you have to declare all the required global >variables in the Source Code by using EXTERN.

You declare them with extern in the ONE place only .. in the shared .h file.  You define them in ONE place only .. in a .c file.

>This also works but this is not advisable

It is STANDARD C and is therefore VERY advisable.  You method does NOT work in a standard compiler.

>as per the software standards in some cases.

If software standards say that you should write non-standard code, then those standards should be redefined ASAP.

>Because this requires additional
>code to write in the source files.

I don't think you understand ...

You put the declarations in a single include file .. just as you did .. but with the keyword 'extern' in front of each one.  Without this, the code will not work with a standard conforming compiler.

It isn't a matter of some optional extra code that is not required.  It is NEEDED.

>He clearly says that all the variables should be recognizable >by all the 6 source files.
>So, My method is correct.

NO IT IS NOT .. it may HAPPEN to wrok for some non-standard conforming compilers. but you NEED the extern infront of each declaration.

>Please Note that. I am not worrying about my points.
>I Love JESUS. He cleanses me with HIS PRECIOUS BLOOD. Tho' I am
>from different religion I have accepted JESUS CHRIST as my
>personal SAVIOUR.

I am happy for you :-)

>If you want you can reject my answer. I don't mind it.

Your (generally incorrect) answer has already been accepted, I'm afraid.  The correct (but rather brief) answer by 'faster' was rejected (for some reason)

>Because HIS LOVE OVERFLOWS
>in my HEART. I want you to know that I Love You.

It's nice to be loved :-)

0
zicokillerCommented:
misbell, please reject this answer so my earlier (correct) comments can be put up as an answer.

I was unable to answer before as the question was still locked.
0
RONSLOWCommented:
What are you on about, zicokiller?  You never made any comments etc. and unfortunately the incorrect answer has already been accepted.

[Or is this a bug in EE with someone else's name appearing on a comment]

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.