ungültige Anwendung von "sizeof' unvollständiger Typ " struct array[]'

Ich versuche zu organisieren, die mein Projekt durch die Aufteilung der Befehle in separate Dateien für eine einfachere Wartung. Die Frage, die ich habe versucht, zu iterieren über das array von Befehlen definiert zur compile-Zeit. Habe ich einen verdummt Beispiel, dass den Fehler reproduziert, die ich immer bin.

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

commands/CMakeLists.txt

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

Befehle/Befehl.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

Befehle/Befehl.c

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

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

Befehle/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

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

Wenn Sie diese

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

tritt der folgende Fehler auf

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

So, wie ich Durchlaufen command_table wenn ich kann nicht einmal bestimmen Sie die Anzahl der Befehle, die in das array?

Ich weiß, es gibt andere Beiträge gibt, mit diesen gleichen Fehler, aber ich habe jetzt eine Weile versucht herauszufinden, warum dies nicht funktioniert und auch weiterhin Versagen:

Sie können nur sizeof command wo seine Größe bekannt ist. Der einzige Ort, wo es ist bekannt, im moment ist command.c, so fügen Sie eine const size_t num_commands = sizeof command / sizeof command[0]; dort, und habe ein extern Erklärung, dass in command.h zu.

InformationsquelleAutor E-rich | 2012-10-13

Schreibe einen Kommentar