C语言编译报错:‘name’存储大小未知,求原因及解决办法
Hey there, let's break down why you're hitting that storage size of 'name' isn't known error—it's all about how C handles type visibility and struct definitions across files.
核心问题:结构体定义的作用域错配 + 头文件依赖颠倒
Here's what's going wrong:
- You defined the actual
struct pointandstruct piecesinboard.c, which is a source file. Source file contents are private to that translation unit—meaningchess.chas no idea what's inside those structs. - Your
board.honly hastypedefstatements, but no underlying struct definitions. Whenchess.cincludesboard.h, the compiler only learns "Pointis an alias for some struct" and "Piecesis an alias for another struct"—but it has no clue how big those structs are, or what's inside them. So when you declarePieces White;, it can't calculate how much memory to allocate, hence the error.
修复步骤:重构头文件与源文件结构
You need to move the full struct definitions into the header file so all source files that use them can see the complete type information. Here's the correct setup:
1. Update board.h with full struct definitions + typedefs
Add the struct definitions before their typedefs, and wrap everything in a header guard to avoid duplicate includes:
#ifndef BOARD_H #define BOARD_H // Define the point struct first, then alias it to Point struct point { short int rank; short int file; }; typedef struct point Point; // Define the pieces struct (now that Point is known), then alias to Pieces struct pieces { Point pawns[8]; Point Knights[2]; Point BBishop; Point WBishop; Point Rooks[2]; Point Queen; Point King; }; typedef struct pieces Pieces; #endif // BOARD_H
2. Clean up board.c
Now board.c only needs to include board.h to access the types, and you can add your board-related function implementations here:
#include "board.h" // Example: function to initialize a player's pieces void init_pieces(Pieces *player) { // Initialize pawns, knights, etc. here }
3. Update chess.c to include the corrected header
Just include board.h and declare your Pieces White; variable—now the compiler has all the info it needs:
#include "board.h" Pieces White; // No more storage size error! int main() { // Your chess logic here return 0; }
Quick Recap
The error happens because the compiler can't see the full definition of Pieces when you declare White in chess.c. By moving the struct definitions into the header file (which is included by all relevant source files), you give the compiler the necessary size information to allocate memory for the variable.
内容的提问来源于stack exchange,提问作者Andrew

