invalid application of 'sizeof' to incomplete type 'struct array[]'

后端 未结 2 1624
鱼传尺愫
鱼传尺愫 2020-12-17 01:14

I am trying to organize my project by splitting commands up into separate files for easier maintenance. The issue I am having is trying to iterate over the array of commands

相关标签:
2条回答
  • 2020-12-17 01:58

    For your sizeof(command_table) to work, it needs to see this:

    static struct command command_table[] = {
        {"help", help_init, help_exec},
    };
    

    But it only sees this:

    extern struct command command_table[];
    

    Seeing that sizeof() can never figure out how many elements are actually in there.

    Btw, there's another problem. static makes the array invisible in all other modules. You have to remove it or workaround it.

    Your options (after removing static) are:

    1. hard-coding the number of elements, e.g.

      extern struct command command_table[3];

    2. defining an extra variable to hold the number of elements:

    commands/command.c

    #include "command.h"
    #include "help_command.h"
    
    struct command command_table[] = {
        {"help", help_init, help_exec},
    };
    
    size_t command_count = sizeof(command_table)/sizeof(command_table[0]);
    

    commands/command.h

    ...
    extern struct command command_table[];
    extern size_t command_count;
    ...
    

    And then you just use command_count.

    0 讨论(0)
  • 2020-12-17 02:12

    Explicit the number of elements of your array in commands/command.h:

    extern struct command command_table[3];
    
    0 讨论(0)
提交回复
热议问题