How can I use a variable in one .c
file when it has been previously defined in another .c
file?

- 5,716
- 8
- 28
- 43
-
12I changed your title. Try to make the title more descriptive, so that 1) people who're able to answer it can see easily what you're asking, and 2) so others who have the same question, will be able to find this so they don't have to ask it again. When looking at the list of questions, we don't need to know that it's a beginner question, but we *do* need to know what the question is about. Just a tip for future questions. :) – jalf Jun 25 '09 at 18:51
6 Answers
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.

- 272,464
- 47
- 358
- 399
-
when the variables are static ,it gives me a link error,"unresolvable symbol ",How to deal with that? – Jun 25 '09 at 18:39
-
18@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 Jun 25 '09 at 18:40
-
Just a remark - what if the owner of the variable is the main.c file, and there is no main.h? – jdepypere May 10 '13 at 18:50
-
2@arbitter: With no header file, you can't share the variable (unless you put `extern int myGlobal;` directly into the source file that wants to access `myGlobal`, but that's a nasty violation of DRY). If you need to share a global from main.c, *create* main.h! – RichieHindle May 10 '13 at 19:00
-
@RichieHindle: Not sure if I'm allowed to make a main.h, but I'll just put it in another file then, thanks! – jdepypere May 10 '13 at 19:08
-
@RichieHindle: Me again - Having trouble having multiple `char i;`'s across documents. I am declaring `char i;` in multiple .c files, without putting `extern char i;` in their corresponding .h files, since I want every file to just have an i for iteration purposes, is it better to make a certain file own it? – jdepypere May 10 '13 at 23:36
-
Multiple `.c` files can have their own `char i;`s without sharing them. That's quite normal. If you're having problems compiling or running what you have, please make a small example and post it as a new question (Stack Overflow likes each question to be self-contained - it isn't a forum, where the discussion can move on to other things). – RichieHindle May 11 '13 at 06:46
-
-
In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.
In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.
In those few rare cases when you need to share a variable between files, do like this:
// file.h
extern int my_var;
// file.c
#include "file.h"
int my_var = something;
// main.c
#include "file.h"
use(my_var);
Never put any form of variable definition in a h-file.

- 195,001
- 40
- 254
- 396
-
I posted this as an answer to an exact duplicate of this post. I feel that some advise regarding the use of global variables was necessary, rather than just blindly teaching bad practice to others without raising a warning first. – Lundin Oct 29 '12 at 14:15
-
2Your post is too opinionated considering you've overstated how rare it is to have a valid case for a global variable. Off the top of my head, binary semaphores that govern resource availability in an embedded system have to be global. Any RTOS-based firmware that shares resources will be littered with global semaphores. Similarly, when a global represents something that truly should be available everywhere, it can be simpler and faster in terms of both speed and development. Also, singletons are basically global variables with some syntactic sugar. Oversimplified? Yes, but conceptually valid. – Anthony Aug 09 '15 at 02:50
-
1@Anthony There is a difference between _global variables_, that are accessible from anywhere in the program (hence global) and _file scope variables_ that are static and only accessible from inside the file they are declared in. The latter is not really bad practice, save for in some multi-threaded scenarios. The examples from your comment should all be implemented with file scope variables. – Lundin Aug 11 '15 at 19:12
-
1So now you're trying to say every global should be a file scope variable, which is incorrect especially in the embedded world unless you think all code should be in one file. How could you know the scope of the variables in code you've never seen? It's extremely common to implement RTOS tasks that share resources and you would never put multiple, completely unrelated tasks in the same file. I'd love to see a way to control access to that resource without global semaphores. This is just a single example of when a global is extremely useful; there are many others. – Anthony Aug 11 '15 at 22:38
-
@Anthony The whole point of private encapsulation is just that: you should not see or care about those variables, outside the file where they are used. Access to such variables should be done through setter/getter functions (that may be inlined). Data belonging to a specific module should be allocated in that very module, and the handling of semaphores if needed, could most likely also be placed inside the setter/getter function. Semaphores by themselves is actually perfect example of this very principle: you don't know or need to know how they are handled internally. – Lundin Aug 12 '15 at 08:37
-
@Anthony The main reason why globals are commonly used in the embedded world is probably because many embedded programmers are electronics people who have "slipped" into the programming branch and lack education/knowledge about proper program design, rather than because of any technical advantage of using globals. I work exclusively with embedded systems programming/program design, and I can't remember the last time I used a (non-constant) global, save for hardware register definitions in a global register map file. I have certainly not used one in the past 10 years. – Lundin Aug 12 '15 at 08:46
-
All of your "probably" and "should" and "should not" statements while calling anyone who uses a global inexperienced and uneducated puts your opinion in context. Tons of people on SO disagree and tons of "real" programmers also disagree. Globals can reduce code complexity and in a highly performance critical system they are an absolute must. You've obviously never worked on a highly constrained embedded system with nearly impossible hard-deadlines where there's literally no time to call functions from an interrupt. Inline isn't valid either because of space requirements. – Anthony Aug 12 '15 at 13:50
-
Besides, you've clearly misunderstand your point if you think using a getter/setter magically fixes the real issue with a global. All you've done is put the problem behind a function call if the getter/setter is available to every function. Here are some discussions where plenty of people disagree with you. [1](http://stackoverflow.com/questions/18547700/when-are-global-variables-actually-considered-good-recommended-practice) [2](http://stackoverflow.com/questions/484635/are-global-variables-bad) [3](http://programmers.stackexchange.com/questions/47923/when-is-it-ok-to-use-a-global-variable) – Anthony Aug 12 '15 at 13:52
-
@Anthony That's all 1980s arguments. We've had inline functions forever and they've been standardized for 16 years. If the compiler inlines your setter/getter function correctly, it will be equivalent to a direct read/write to a variable. If it doesn't, well then the problem is with the compiler. And in the rare case where you come across very hard real-time requirements, which as it happens I occasionally do in my line of work, you'd be watching the disassembly and adapt the code accordingly. Perhaps write the critical parts in assembler, in which case no C practice is applicable anyhow. – Lundin Aug 12 '15 at 14:16
-
@Anthony Besides, if you write the super-critical ISR in another module than the one containing the variables that need to be modified, your whole program design is flawed. That's almost always what the "global" debate boils down to: design the program correctly instead. And the whole "global" debate is meaningless to look at since some people define the term global as any variable declared outside a function, while others define it as a globally accessible variable. – Lundin Aug 12 '15 at 14:20
-
@Lundin just come to this post, now can you say what about below problem, https://stackoverflow.com/questions/61592399/do-i-really-needed-accessor-functions-to-access-global-variable-from-another-fil – user2520119 May 05 '20 at 07:33
-
From your answer, I came to know that make global variable file specific using static and introduce inlined getter\setter API to give access to other files. That inlined getter\setter will be doing the same as the global variable directly modify in another file. So what's the benefit behind this private, getter\setter design? code readability? data integrity (of course not as other files can still modify that variable using setter API)? – user2520119 May 05 '20 at 07:50
-
@user2520119 Private encapsulation. There's many books written about OO design explaining this. Most importantly, you shouldn't have a "tight coupling" between two modules, where they know about each other's internals. In the simple case of a single variable, this might not seem meaningful, but when things grow more complex, so do the advantages of private encapsulation. – Lundin May 05 '20 at 08:43
-
@Lundin Ok and for that reason, OOPs concept introduced(C++ or JAVA) which helps to maintain data hiding, more flexibility, reusability, etc. But when it comes to C then I think we are adding more overhead to achieve this OOPs like concept. suppose I have 3 files and among them one global variable shared(`i.e bool network_connected`) and that variable can be `true or false`. – user2520119 May 05 '20 at 10:02
-
If I consider your design(private, getter/setter API) in this case then I don't think private encapsulation makes any sense as other file\module ultimately know that I am setting it's value `true\false` (here hiding method implementation not truly achieved). For complex methods this is useful I think but again it will add function call overhead. – user2520119 May 05 '20 at 10:02
-
@user2520119 Proper language design is language independent. The presence of a global variable that "must" be shared with 3 unrelated files is a design mistake. Instead you should probably have a local variable in a caller, which in turn calls the 3 different modules. I work almost exclusively with hard real-time systems, and even in such systems, it will be very hard to find an argument about why that design is "overhead". Readability/maintainability and loose coupling is almost always the preferred choice. Don't prematurely optimize the code until you have actual performance bottlenecks. – Lundin May 05 '20 at 10:24
-
@Lundin It's not always a design mistake but many designs itself gives hint to use a global variable. Suppose three modules `wifi`, `bluetooth` and `TCP\IP` are set one global variable `i.e network_status` to numerious state value. Now other fourth module called `application` have state machin running which do different task according state value (`i.e network_status`). So here how you avoid to use of global variable? – user2520119 May 05 '20 at 10:38
-
@user2520119 State machines in particular should only set their state variable at one single point in the program, or you get "globals spaghetti" as well as "flag spaghetti". I've trouble-shooted far too many broken state machines. Your state machine calling code should look something like `network_status = state_machine[state](); if(network_status == ERROR) { error_handler(network_status); } else { state = set_state(state); }` Where `state_machine` is an array of function pointers to the various states and `set_state` is the _only_ place in the program where a state change can occur. – Lundin May 05 '20 at 14:35
- Try to avoid globals. If you must use a global, see the other answers.
- Pass it as an argument to a function.

- 42,585
- 14
- 91
- 146
-
7How do you handle interrupts then? Say an interrupt is triggered and I want to read a value on a pin, how would one return that value without writing it to a global variable? – realityinabox Jan 22 '15 at 20:13
-
@realityinabox — That's an incredibly domain specific answer, whereas the OP's question was much more broad. In such a situation, you might very well need a global. (This is an incredibly old answer, and I omitted a lot of details about why — threading, re-entrancy, code readability — as to why a global is typically not the best choice.) – Thanatos Jan 27 '15 at 18:55
-
7@Thanatos It's not 'incredibly' anything. Unless you think the extensive world of embedded development is something about which a beginner would never inquire, then your answer is too narrow and specific. There are many other reasons to use globals outside of what you apparently believe to be the normal use of C if there is such a thing. Lastly, there's absolutely no context in the OP's question, so your statement about it being broad is an assumption. The OP very well could have been asking about interrupts. – Anthony Aug 09 '15 at 22:12
-
1@realityinabox would you please elaborate on why are global variables should be avioded in generic? – Dávid Tóth May 02 '16 at 08:38
-
2@Thanatos it really irks me when people say that things /should/ be some way without saying why, that's completely worthless information to anyone reading it, if the feature is there then it is intended to be used. – Jose V Apr 26 '17 at 05:47
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.

- 11,479
- 5
- 49
- 73
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.

- 8,636
- 1
- 20
- 21