tags:

views:

1048

answers:

5

beginner question about C declaration:

In a .c file, how to use variables defined in another .c file?

+2  A: 

if the variable is : int foo;

in the 2nd C file you declare: extern int foo;

JeffP
+11  A: 

In fileA.c:

int myGlobal = 0;

In fileA..h

extern int myGlobal;

In fileB.c:

#include "fileA.h"
myGlobal = 1;

So this is how it works:

  • the variable lives in fileA.c
  • fileA.h tells the world that it exists, and what its type is (int)
  • fileB.c includes fileA.h so that the compiler knows about myGlobal before fileB.c tries to use it.
RichieHindle
when the variables are static ,it gives me a link error,"unresolvable symbol ",How to deal with that?
Jinx
@jfq: "static" in non-class context means "confined to this translation unit". it's essentially the opposite of "extern". You can't have both at the same time.
rmeador
+1  A: 

Those other variables would have to be declared public (use extern, public is for C++), and you would have to include that .c file. However, I recommend creating appropriate .h files to define all of your variables.

For example, for hello.c, you would have a hello.h, and hello.h would store your variable definitions. Then another .c file, such as world.c would have this piece of code at the top:

#include "hello.h"

That will allow world.c to use variables that are defined in hello.h

It's slightly more complicated than that though. You may use < > to include library files found on your OS's path. As a beginner I would stick all of your files in the same folder and use the " " syntax.

AlbertoPL
A: 

The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.

That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

bluebrother
+2  A: 
  1. Try to avoid globals. If you must use a global, see the other answers.
  2. Pass it as an argument to a function.
Thanatos