[英]Redefinition errors in .h files
//list.h file
typedef struct _lnode{
struct _lnode *next;
size_t row;
size_t column;
short data;
}lnode;
typedef struct _llist{
struct _lnode *head;
size_t size;
}llist;
//matrix.h file
typedef struct _matrix{
size_t width;
size_t height;
size_t k;
int **data;
}matrix;
//smatrix.h file
#include "list.h"
#include "matrix.h"
typedef struct _smatrix{
size_t width;
size_t height;
size_t k;
llist data;
}smatrix;
smatrix* make_smatrix(matrix *m);
smatrix.h文件包含list.h文件和matrix.h文件。 如果我在smatrix.h文件中包含這些頭文件,那么我得到
redefinition of 'lnode'. redefinition of '_llist' and redefinition of '_matrix' errors.
如果我從smatrix.h文件中獲取了那些heder文件,那么錯誤就會消失,但它會在函數參數中抱怨矩陣類型。 我想調用list.h中定義的函數和smatrix.c文件中的matrix.h文件。我該怎么辦? 提前致謝..
多重夾雜物可能存在的問題。
嘗試用#ifndef
保護你的頭文件, 在這里閱讀它
文件列表
#ifndef _LISTH_
#define _LISTH_
<your code>
#endif
file matrix.h
#ifndef _MATRIXH_
#define _MATRIXH_
<your code>
#endif
如果你在標題包含中有一個循環,它將阻止你也有重新定義。
你需要在頭文件中包含警衛 。
從您發布的代碼中我認為缺少的是每個* .h文件的開頭:
#ifndef _some_unique_identifier_for_each_header
#define _some_unique_identifier_for_each_header
...header contents
#endif //_some_unique_identifier_for_each_header
或者a
#pragma once
如果您的編譯器支持它。
如果沒有這個,如果從各種來源多次包含標題,則會出現與重新定義相關的錯誤。
你可能包括smatrix.h
和list.h
在其他一些文件。 你應該避免這種情況。 通常的方法是使用include guards
。
這些是您在文件開頭用#ifdef
檢查的宏(最后是#endif
),並在#ifdef ... #endif
#define
,從而確保即使您確實包含相同的文件多個次,編譯器只會在第一次讀取它一次,並跳過所有其余的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.