Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring,initializing and using a global variable in same header file

Tags:

c

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.

like image 314
mousey Avatar asked Dec 13 '22 11:12

mousey


1 Answers

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.

like image 162
littleadv Avatar answered Apr 13 '23 00:04

littleadv