Ok, I'm looking to define a set of memory addresses as constants in a .h file that's used by a bunch of .c files (we're in C, not C++). I want to be able to see the name of the variable instead of just seeing the hex address in the debugger... so I want to convert the #defines I currently have into constants that are global in scope. The problem is, if I define them like this:
const short int SOME_ADDRESS = 0x0010
then I get the dreaded "multiple declarations" error since I have multiple .c files using this same .h. I would like to use an enum, but that won't work since it defaults to type integer (which is 16 bits on my system... and I need to have finer control over the type).
I thought about putting all the addresses in a struct... but I have no way (that I know of) of setting the default values of the instance of the structure in the header file (I don't want to assume that a particular .c file uses the structure first and fills it elsewhere.. I'd really like to have the constants defined in the .h file)
It seemed so simple when I started, but I don't see a good way of defining a globally available short int constant in a header file... anyone know a way to do this?
thanks!
Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.
Although you should try to avoid the use of global variables, it is generally permissible to use global constants in a program. A global constant is a named constant that is available to every function in a program.
1) Use a static local variable within a function. It will retain its value between calls to that function but be 'invisible' to the rest of the program. 2) Use a static variable at file scope (ie declared outwith all functions in the source file). It will be 'invisible' outside that source file.
Global constants are fine.
Declare the constants in the header file using extern
:
extern const short int SOME_ADDRESS;
then in any, but only one, .c
file provide the definition:
const short int SOME_ADDRESS = 0x0010;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With