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 var
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.
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.