Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying char array size in extern statement for sizeof command

There was

char B[200];

in the static library. It was referred as

extern char B[];  // (1)

in the header that is included in the client's code. Once I needed to use sizeof(B) compiler complained and changing to

extern char B[200]; // (2)

calmed compiler down.

Library and client code are c++, but it uses C linkage (header's extern declarations surrounded by

extern "C" { ... }

Is there any potential problem if I use (2) instead of (1)?

P.S. I put 200 for simplicity. it is a constant defined in the header file that comes with the library.

library header:

#define MAXLEN 200

Actually even if it is not a library, but in a separate file(compilation unit) the problem is similar.

Is there any way that (1) could've used in this big old code that I might break by using (2)?

like image 264
sny Avatar asked Dec 05 '25 08:12

sny


1 Answers

If the library implementation ever changes the size of B you'll have a mismatch and possibly a variety of bugs to hunt down. The library writer should provide a constant that describes the size of the array. As noted in a comment the library writer could easily provide this via a constant or function written in terms of sizeof(b) to make it very resilient to changes in the library.

like image 200
Mark B Avatar answered Dec 07 '25 21:12

Mark B