4

I am actually trying to use a variable that is initialized in a header file(say x.h) and want to use same variable inside inlined code in the same header file. The same variable is modified in another file (say y.c). How can i do this ? I would like to know a good way of doing this.

2 Answers 2

7

Using the extern reserved word.

Never create variables in '.h' files, it's a bad practice that leads to bugs. Instead, declare them as extern everywhere you need to use them and declare the variable itself only in a single '.c' file where it will be instantiated, and linked to from all the other places you use it.

Sign up to request clarification or add additional context in comments.

Comments

6

You can declare the global variable in the header file as extern, and then define it inside a code-module (i.e., ".c" file). That way you won't end up with multiple definition errors thrown by the linker.

So for example in your header file, a globally available int named my_global_var would have a declaration in a .h file that looks like:

extern int my_global_var;

Then inside a single .c file somewhere you would define and initialize it:

int my_global_var = 0;

Now you can use my_global_var in any other code module that includes the appropriate header file and links with the proper .c file containing the definition of the global variable.

6 Comments

i will be using the variable in the header file itself (The code is "inlined"). So there is no x.c itself
?? ... No .c file anywhere?? ... you declared it extern in the header file, but it's actually definied in a .c file. You can now use the global var in the header file without any issues.
Its just y.c ! But i will be using y.c way after using inlined code in x.h
That's fine ... declare the variable as extern in x.h, then define the global var in y.c, and when you compile your code, make sure that y.o (the object file compiled from y.c) is included by the linker in your final program. An inlined function in x.h can use the externally defined global variable in y.c without any issues at that point (you will also have to write #include x.h in your y.c file).
Okay, since you mention "module x", that means there is an x.c as well, right? If that's the case, then define the global variable in x.c. It really doesn't matter what .c file you define the global var in as long as it includes the header file you declared it extern in, and any other file that tries to use the global var includes the appropriate header file. In fact, you don't even need the header ... you can just declare extern int my_global_var in any other place you want access to my_global_var, although doing it inside a header file is the best design-choice.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.