Constant-sized global arrays in C

I am trying to find a better way to define a global array with a constant size, and I came 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 cannot get the ASIZE value from GDB. I think the third option is best because I can still reset the const value, but it also seeps into another macro. I can undef macro after defining the array and const , but if #define and const are in a separate file from the array declaration, then it gets a little hairy.

Is there a better way?

+4
source share
4 answers

You are dealing with a GDB problem, not a C problem. You can also do # 4, which is probably better than # 3.

 enum {ASIZE = 10}; static const int ASIZE_FOR_GDB = ASIZE; int array[ASIZE]; 
+5
source

Doing something for the debugger is wrong. By the way, gdb knows about this if you compile your code on the right .

Some languages, such as C and C ++, provide a way to define and call "preprocessor macros" that expand into token strings. gdb can evaluate expressions containing macros, show macroexchange results, and show macro definitions, including defined ones.

Version 3.1 and later of gcc, the gnu C compiler, provides a macro if you specify the -gdwarf-2 and -g3 ; the former option asks for debug information in Dwarf 2 format, and the latter asks for "additional information".

+8
source

I understand that you define a constant, using it later to determine the size of one or more arrays, and also want the constant to be a character, preferably without a messy namespace. (If it was a question of exporting the size of a single array, I would instead suggest sizeof(array) / sizeof(*array) as missing).

 static const int ASIZE = 10; #define ASIZE 10 int array[ASIZE]; 

There is a variable with the desired value that will be in the object file, but the preprocessor macro obscures it with the value itself, so the array definition will also be successful.

However, you may find the need to duplicate the expression of the value ugly. Would it be nice if we could define a variable in terms of a macro?

 static const int ASIZE = #define ASIZE 10 ASIZE; int array[ASIZE]; 

I'm not sure if this is actually the best idea, not only the one above, but it works (and I could not get gcc to take offense at it) and does not contain duplication, except for the identifier. And this is funny.

+5
source

Since you know that array is a global array (not just a pointer), you can find its length using

 sizeof(array) / sizeof(*array) 

without requiring an additional variable for this.

+2
source

Source: https://habr.com/ru/post/1384741/


All Articles