檔案工具.h:
//some macro definitions
struct name;
//other function prototypes
檔案工具.c:
#include "tools.h"
struct name
{
FILE *src;
int value;
}
//definitions of functions declared in tools.h
檔案main.c:
#include <stdio.h>
#include "tools.h"
int main()
{
struct name *ptr;
ptr = malloc(sizeof(struct name));
ptr->FILE = fopen(filename, "r");
ptr->value = 12;
...
}
起初,我使用以下方法構建 tools.o:
$ gcc tools.c -c
沒有任何錯誤或警告,tools.o在當前目錄中構建。現在,我嘗試通過使用來構建可執行檔案:
$ gcc main.c tools.o -o exe
并且我得到了相同型別的錯誤(所有錯誤都是相同型別的,由于訪問 struct 元素而導致)。這是我得到的那個錯誤的樣本:
main.c: In function ‘main’:
main.c:17:22: error: invalid use of undefined type ‘struct name’
17 | buffer = malloc(ptr->value 1);
請解釋為什么會發生這種情況以及我在鏈接時或在我的代碼中做錯了什么。
uj5u.com熱心網友回復:
工具.h 檔案
#ifndef TOOLS_H
#define TOOLS_H
#include <stdio.h>
struct name
{
FILE *src;
int value;
};
int foo(struct name*);
struct name *bar(double, FILE*, const char *); //prototypes of functions defined in tools.c
#endif
工具.c
#include "tools.h"
int foo(struct name*)
{
/* ... */
}
struct name *bar(double, FILE*, const char *)
{
/* ... */
}
uj5u.com熱心網友回復:
看起來您對結構的前向宣告和結構宣告(定義型別)有些困惑。
從前向宣告:
前向宣告是程式員尚未給出完整定義的識別符號(表示物體,例如型別、變數、常量或函式)的宣告。
中tools.h,這
struct name;
是結構的前向宣告struct name。請注意,它宣告了一個不完整的型別,因為此時的規范[定義內容的串列]是struct name未知的。
您已經包含tools.h在編譯器中main.c并且在編譯時main.c找不到規范,struct name因此在使用它的陳述句上拋出錯誤。
在tools.c中,您正在宣告struct name(它定義了一個型別):
struct name
{
FILE *src;
int value;
};
編譯時tools.c,編譯器知道結構的規范,struct name因此編譯成功。
另一篇文章 [by @0___________] 給出了解決此問題的適當方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532228.html
標籤:C海合会结构静态链接
下一篇:確定無符號整數的范圍
