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 に答える