8

我正在尝试通过将命令拆分为单独的文件来组织我的项目,以便于维护。我遇到的问题是尝试迭代在编译时定义的命令数组。我创建了一个简化的示例来重现我遇到的错误。

.
├── CMakeLists.txt
├── commands
│   ├── CMakeLists.txt
│   ├── command.c
│   ├── command.h
│   ├── help_command.c
│   └── help_command.h
└── main.c

./CMakeLists.txt

PROJECT(COMMAND_EXAMPLE)

SET(SRCS main.c)
ADD_SUBDIRECTORY(commands)

ADD_EXECUTABLE(test ${SRCS})

命令/CMakeLists.txt

SET(SRCS ${SRCS} command.c help_command.c)

命令/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

命令/command.c

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

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

命令/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

命令/help_command.c

#include "help_command.h"

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

int help_command_exec(void)
{
    return 0;
}

./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;
}

如果你运行这个

mkdir build && cd build && cmake .. && make

发生以下错误

path/to/main.c:6:40: error: invalid application of 'sizeof' to incomplete type 'struct command[]'

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

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

4

2 回答 2

18

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

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

但它只看到这个:

extern struct command command_table[];

看到它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]);

命令/command.h

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

然后你只需使用command_count.

于 2012-10-13T12:43:03.100 回答
1

在 中显式显示数组的元素数commands/command.h

extern struct command command_table[3];
于 2012-10-13T12:38:50.253 回答