Reputation: 95
Currently I have subroutines and global variables defined above my main()
. I'm trying to create a library in C. Can I declare the global variables in the header file?
Upvotes: 4
Views: 12841
Reputation: 2096
Try to minimize the use of global variables as they make a program less readable and more error-prone. A library should be used trough its interface (passing data back and forth between the functions it provides), not by accessing global variables.
In situations where there's really no other way, such as sharing data with a interrupt service routine for example, try to keep the variables contained to that compilation unit by making them static, so they cannot interfere with other libraries.
If for some reason you really need a global variable, define it in the code file (c file) and declare it as extern in the header file.
Upvotes: 1
Reputation: 406
There should be no problem, or you can declare them in the .c and use extern in the .h file
Upvotes: 0
Reputation: 726629
Can I declare the global variables in the header file?
Yes, you can declare your global variables in the header file. However, these must be declarations, not definitions of your global variables.
In other words, the header should say
// This goes into the header
extern int my_global_int;
and the C file should say
int my_global_int;
Note: The fact that you can do it does not mean that you should do it. Exposing "raw" global variables from a library is a bad practice, because users of your library can do unexpected things to them.
A better approach would be hiding your globals by making them static
, and exposing functions to manipulate them instead:
// This goes into the header
int get_global();
void set_global(int n);
// This goes into the C file
static int my_former_global;
int get_global() {
return my_former_global;
}
void set_global(int n) {
if (<n-is-valid>) {
my_former_global = n;
}
}
Upvotes: 16
Reputation: 1929
The answer is yes and no. Yes you can declare global variables in a header file, but no you shouldn't declare global variables, especially when you want to deploy a library. Or at least choose the variables that are going to global space with great care and then try to rethink if they are really useful or if it would be better to hold variables in some context structures.
Upvotes: 0