'extern' keyword for an array

In file AAA.c

const char CMD_Fire[] = "FIRE";

In file BBB.c

extern const char CMD_Fire[];

It seems that, the compiler is not able to know the size of CMD_Fire[], when compiling BBB.c

So, I have to hard code the size of CMD_Fire[] in BBB.c

Then, if I change the command to "Fire it!", I will need to change the size of CMD_Fire[] everywhere.

Is there any skill to handle this?

Parents
  • Of course it isn't - because you have not provided it with that information!

    This has nothing to do with ARM or Keil - this is standard 'C' behaviour!

    A 'C' compiler "sees" only one "compilation unit" at a time. In this case, the only information available in the "compilation unit" is your extern declaration:

    extern const char CMD_Fire[];
    


    which, clearly, contains no length information!

    In this particular case, since it's a string, the best approach would probably be to use string functions - which will automatically detect the end of the string (and, hence, its length) at run-time.

    Alternatively, proceed as follows:

    cmd.h

    #define LEN_CMD_FIRE 5 // Remember to count the NUL!
    
    extern const char CMD_Fire[LEN_CMD_FIRE];
    

    AAA.c

    #include "cmd.h"
    
    const char CMD_Fire[LEN_CMD_FIRE] = "FIRE";
    

    BBB.c

    #include "cmd.h"
    
    // now you can use CMD_Fire and LEN_CMD_FIRE...
    

Reply
  • Of course it isn't - because you have not provided it with that information!

    This has nothing to do with ARM or Keil - this is standard 'C' behaviour!

    A 'C' compiler "sees" only one "compilation unit" at a time. In this case, the only information available in the "compilation unit" is your extern declaration:

    extern const char CMD_Fire[];
    


    which, clearly, contains no length information!

    In this particular case, since it's a string, the best approach would probably be to use string functions - which will automatically detect the end of the string (and, hence, its length) at run-time.

    Alternatively, proceed as follows:

    cmd.h

    #define LEN_CMD_FIRE 5 // Remember to count the NUL!
    
    extern const char CMD_Fire[LEN_CMD_FIRE];
    

    AAA.c

    #include "cmd.h"
    
    const char CMD_Fire[LEN_CMD_FIRE] = "FIRE";
    

    BBB.c

    #include "cmd.h"
    
    // now you can use CMD_Fire and LEN_CMD_FIRE...
    

Children
More questions in this forum