'sizeof'无效应用于不完整类型'struct array []'

E-r*_*ich 5 c arrays sizeof

我试图通过将命令分成单独的文件来组织我的项目,以便于维护.我遇到的问题是尝试迭代编译时定义的命令数组.我创建了一个愚蠢的例子来重现我得到的错误.

.
??? CMakeLists.txt
??? commands
?   ??? CMakeLists.txt
?   ??? command.c
?   ??? command.h
?   ??? help_command.c
?   ??? help_command.h
??? main.c
Run Code Online (Sandbox Code Playgroud)

./CMakeLists.txt

PROJECT(COMMAND_EXAMPLE)

SET(SRCS main.c)
ADD_SUBDIRECTORY(commands)

ADD_EXECUTABLE(test ${SRCS})
Run Code Online (Sandbox Code Playgroud)

命令/的CMakeLists.txt

SET(SRCS ${SRCS} command.c help_command.c)
Run Code Online (Sandbox Code Playgroud)

命令/ command.h

#ifndef COMMAND_H
#define COMMAND_H

struct command {
    char* name;
    int   (*init)(int argc, char** argv);
    int   (*exec)(void);
};

extern struct command command_table[];

#endif
Run Code Online (Sandbox Code Playgroud)

命令/ COMMAND.C

#include "command.h"
#include "help_command.h"

struct command command_table[] = {
    {"help", help_init, help_exec},
};
Run Code Online (Sandbox Code Playgroud)

命令/ help_command.h

#ifndef HELP_COMMAND_H
#define HELP_COMMAND_H

int help_command_init(int argc, char** argv);
int help_command_exec(void);

#endif
Run Code Online (Sandbox Code Playgroud)

命令/ help_command.c

#include "help_command.h"

int help_command_init(int argc, char** argv)
{
    return 0;
}

int help_command_exec(void)
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

./main.c

#include <stdio.h>
#include "commands/command.h"

int main(int argc, char** argv)
{
    printf("num of commands: %d\n", sizeof(command_table) / sizeof(command_table[0]));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果你运行这个

mkdir build && cd build && cmake .. && make
Run Code Online (Sandbox Code Playgroud)

发生以下错误

path/to/main.c:6:40: error: invalid application of 'sizeof' to incomplete type 'struct command[]'
Run Code Online (Sandbox Code Playgroud)

那么,command_table如果我甚至无法确定数组中的命令数量,我该如何迭代呢?

我意识到还有其他帖子有同样的错误,但我花了一段时间现在试图弄清楚为什么这不起作用并继续失败:

Ale*_*nze 15

为了你sizeof(command_table)的工作,它需要看到这个:

static struct command command_table[] = {
    {"help", help_init, help_exec},
};
Run Code Online (Sandbox Code Playgroud)

但它只看到这个:

extern struct command command_table[];
Run Code Online (Sandbox Code Playgroud)

看到这一点sizeof()永远无法弄清楚实际上有多少元素.

顺便问一下,还有另外一个问题.static使数组在所有其他模块中不可见.您必须将其删除或解决它.

您的选择(删除后static)是:

  1. 硬编码元素的数量,例如

    extern struct command command_table[3];

  2. 定义一个额外的变量来保存元素的数量:

命令/ 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]);
Run Code Online (Sandbox Code Playgroud)

命令/ command.h

...
extern struct command command_table[];
extern size_t command_count;
...
Run Code Online (Sandbox Code Playgroud)

然后你就用了command_count.