14

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!

hmjd
  • 120,187
  • 20
  • 207
  • 252
Kira Smootly
  • 207
  • 2
  • 4
  • 6

2 Answers2

29

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;
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • if I do that, won't I have to know that that particular .c file is called first? or if they are defined globally in that .c file, will the definition be accomplished before any function is called? – Kira Smootly Mar 12 '12 at 14:09
  • No, there is nothing to be called to initialize the constants and the definition will be present before anything attempts to use them. Just ensure that the `.o` (or `.obj`) file of the `.c` file where the constants are defined is linked into the final binary. – hmjd Mar 12 '12 at 14:12
0

If you're compiling with gcc, you can add the -ggdb3 switch, which will tell gcc to store macro information (i.e. #defines) so that they can be used inside gdb.

Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319