sizeof(array) incomplete type not allowed (E70)

27 Dec 2010

extern const char cmdNames[];

this won't compile

     for(i=0, k=0;i<sizeof(cmdNames);i++)

unless I specify array dimension, like

extern const char cmdNames[58];

Because complier reserved memory for this array, it should know the size of that array!

For now, I have to figure out by myself what is this array size.

Am I using sizeof() correctly ?

27 Dec 2010

The compiler compiles each .c/.cpp into a module first before the linker then links these together. So at compile time, the compiler doesn't know the extern array size defined in another module.

This is generally where #define comes in. Have your own .h file that's included in every .c/.cpp file you create. Then in the header have something like

#define MY_ARRAY_SIZE 58

And then in each .c/.cpp file, #include your header and then use the macro thus

extern const char cmdNames[MY_ARRAY_SIZE];
27 Dec 2010

I shoudl also have mentioned you can use the macro in place of sizeof() thus

    for(i=0, k=0;i<sizeof(cmdNames);i++)

becomes

    for(i=0, k=0;i<MY_ARRAY_SIZE;i++)
27 Dec 2010

Another solution:

file1.cpp

const char * cmdNames[] = {
  "cmd1",
  "cmd2",
  ...
  "cmdN",
};
int numCmds = sizeof(cmdNames)/sizeof(cmdNames[0]);

(note that to get the number of items you need to divide the whole array size by the size of one item)

file2.cpp

extern const char * cmdNames[];
extern int numCmds;
for(int i=0; i < numCmds; i++)
{
 ...
}
27 Dec 2010

Thanks,

This also works:

file.h

const char cmdNames[]=
   {
      'l','i','s','t',0,
      'v','e','r',0,
      'h','e','l','p',0,
      'f','e','e','d','b','a','c','k',0,
      'e','c','h','o',0,
      's','w','R','e','a','d',0,
      's','w','R','e','a','d','A','l','l',0,
      's','w','I','n','i','t',0,
      'i','n','i','t',0,
      0
   };

file.c

#include "file.h"

But that puzzles me.

I had so much difficulties to find a way to get rid of multiple defines, that I ruled out this solution.

This file.h is included in many other files and the compiler does not complain.

I'm not to hot about the #define solution, because the header file is auto generated by another application, and I would have to modify the code. 

27 Dec 2010

By doing that you are creating "globals" but they are global "only to that module" (.c/.cpp file). You are just repeating the data. If the compiler is smart enough it'll notice this and optimise the duplication out. Otherwise your just wasting flash space with duplicate data.

As for the .h solution. Your project is allowed more than one custom header file. You can have one automagically created and one that's hand created. Or use Igor's method.