Link to home
Start Free TrialLog in
Avatar of drewman75
drewman75

asked on

passing string global variable

Hi All,
  I am sure this is an easy one, but for some reason, I can't figure it out.  I am trying to set up a global variable string in a header file, initialize the value in main.c and then access the variable in a function in another .c file.  Whenever I try to access from that secondary file, I get nothing.  Here is a simpified example below that I hope will show what I am trying to do.


/* variables.h */

char  filename[30];


/* main.c */

#include "variable.h"

strcpy(filename, "filename.dat");
print_filename();

/* other.c */

#include "variable.h"

print_filename()
{
   printf("%s", filename);
}


For some reason, the value of filename is always NULL in the other.c app.  Why is this? What am I doing wrong?  Thanks.
ASKER CERTIFIED SOLUTION
Avatar of brettmjohnson
brettmjohnson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Kent Olsen
Hi drewman75,

Note that some (particularly) older compilers don't allow you to declare a variable as "extern" (as Brett suggests) and initialize it (give it a default value) in the same object.

Otherwise, Brett's 100% right.  He's like that.  :)


Good Luck!
Kent
Hi brettmjohnson,

Isnt:

extern char filename[30];

a little better? I know it used to be not allowed but it seems to work nowadays on compilers I use.

Paul
Avatar of cryptosid
cryptosid

I thought the extern declaration should be in main.c and other files that are going to share the common variable and not in the variables.h, the variables.h should contain the global declaration.


correct me if i am wrong..

Regards,
Siddhesh
What is happening here is the actual data is in the 'main' module (sort-of) and the header is telling all the other modules that it exists and that the linker will be told about its final location so they have to register all references to it for the linker to access at final build time.

The style you mentioned would create a new instance for every module that includes the header.

Paul
Hi PaulCaswell,

Ah! I overlooked the 'purpose' the program is being written..yes you are correct.


Regards,
Siddhesh

try this one

#include "variable.h"

/*main.c*/

int main()
{
 strcpy(filename, "filename.dat");
 #include "other.h"

}
/* other.h */
 printf("%s", filename);