Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant size global arrays in C

Tags:

c

gdb

I'm trying to figure out there best way to define a global array with a constant size and I've come to the following options, all with their own flaws.

// 1:
#define ASIZE 10
int array[ASIZE];

// 2:
enum {ASIZE = 10};
int array[ASIZE];

// 3:
#define ASIZE_DEF 10
static const int ASIZE = ASIZE_DEF;
int array[ASIZE_DEF];

The problem with the first two is that I can't get the value of ASIZE from GDB. I guess the third option is best because I can still dump the value of the const, but it also leaks in another macro. I can undef the macro after defining the array and const but if the #define and the const are in a separate file from the array declaration, then it gets a bit hairy.

Is there a better way?

like image 959
dschatz Avatar asked Dec 01 '22 07:12

dschatz


1 Answers

Doing something for the sake of the debugger is wrong. Incidentally, gdb knows about this if you compile your code right.

Some languages, such as C and C++, provide a way to define and invoke “preprocessor macros” which expand into strings of tokens. gdb can evaluate expressions containing macro invocations, show the result of macro expansion, and show a macro's definition, including where it was defined.

Version 3.1 and later of gcc, the gnu C compiler, provides macro information if you specify the options -gdwarf-2 and -g3; the former option requests debugging information in the Dwarf 2 format, and the latter requests “extra information”.

like image 151
cnicutar Avatar answered Dec 15 '22 16:12

cnicutar