[英]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
PROJECT(COMMAND_EXAMPLE)
SET(SRCS main.c)
ADD_SUBDIRECTORY(commands)
ADD_EXECUTABLE(test ${SRCS})
SET(SRCS ${SRCS} command.c help_command.c)
#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
#include "command.h"
#include "help_command.h"
struct command command_table[] = {
{"help", help_init, help_exec},
};
#ifndef HELP_COMMAND_H
#define HELP_COMMAND_H
int help_command_init(int argc, char** argv);
int help_command_exec(void);
#endif
#include "help_command.h"
int help_command_init(int argc, char** argv)
{
return 0;
}
int help_command_exec(void)
{
return 0;
}
#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
)是:
硬編碼元素的數量,例如
extern struct command command_table[3];
定義一個額外的變量來保存元素的數量:
命令/ 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.