Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global constants without using #define

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!

like image 278
Kira Smootly Avatar asked Mar 12 '12 13:03

Kira Smootly


People also ask

Should you avoid using global variables?

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.

Are global constants acceptable?

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.

How do you not use global variables?

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.

Are global constants bad?

Global constants are fine.


1 Answers

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;
like image 96
hmjd Avatar answered Oct 13 '22 00:10

hmjd