beginner question about C declaration:
In a .c file, how to use variables defined in another .c file?
beginner question about C declaration:
In a .c file, how to use variables defined in another .c file?
if the variable is : int foo;
in the 2nd C file you declare: extern int foo;
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:
int
)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.
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 #include
s 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.