-2

I have a file1.c and file2.c. If I define a variable in file1.c, and assign a value to it, how can I access this variable from file2.c?

How should I declare the variable in file1.c and how to retrieve the value from file2.c?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user2131316
  • 3,111
  • 12
  • 39
  • 53
  • See also [What are `extern` variables in C?](http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c/1433387#1433387) – Jonathan Leffler May 20 '13 at 15:36

1 Answers1

1

A.c:

int a;

A.h:

extern int a;

That's how. But don't. It's a bad idea.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • I'd also advice against abusing it.. you can usually make a model where you pass these variables as function arguments. Helps keep track of stuff. – Boyko Perfanov May 20 '13 at 15:34
  • can I declare int a; in A.c, and use it like extern int a; in B.c, because I do not need a A.h for A.c – user2131316 May 20 '13 at 15:35
  • @user2131316, yes you can. Header files are essentially just copied when included in pre-processing. Using a header will just save you the need of editing the extern declaration at every file, if you use it more than once. But anyway, I advise you to look for a solution that doesn't require globals. – StoryTeller - Unslander Monica May 20 '13 at 15:38
  • ok, thank you, but why do not, and it is a bad idea? – user2131316 May 20 '13 at 15:39
  • @user2131316, It increases coupling between translation units, for one. Exposing a global means other translation units know about your inner workings, how you represent data. And even worse, they can modify it without letting you know about it. – StoryTeller - Unslander Monica May 20 '13 at 15:41
  • @user2131316, so for instance. If you need `a` to always be in a certain range, you can no longer guarantee that assertion. Since another programmer can access it and change it directly in another translation unit. It's a bit of an artificial case, but I think you get the picture. – StoryTeller - Unslander Monica May 20 '13 at 15:44