簡體   English   中英

'sizeof'無效應用於不完整類型'struct array []'

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

我試圖通過將命令分成單獨的文件來組織我的項目,以便於維護。 我遇到的問題是嘗試迭代編譯時定義的命令數組。 我創建了一個愚蠢的例子來重現我得到的錯誤。

.
├── 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

我意識到還有其他帖子有同樣的錯誤,但我花了一段時間現在試圖弄清楚為什么這不起作用並繼續失敗:

要使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

commands/command.h數組元素的數量:

extern struct command command_table[3];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM