質問

port.h、port.c、およびmain.cというヘッダーファイルがあります

次のエラーが表示されます: 'ports'は未定義の構造体 'port_t'を使用します

.hファイルで構造体を宣言したので、.cファイルに実際の構造体があれば問題ないと思いました。

port.cファイルの一部のデータを非表示にするため、前方宣言が必要です。

port.hには次のものがあります:

/* port.h */
struct port_t;

port.c:

/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};

main.c:

/* main.c */
#include <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}

ご提案ありがとうございます

役に立ちましたか?

解決

残念ながら、コンパイラはmain.cのコンパイル中に port_t のサイズ(バイト単位)を知る必要があるため、ヘッダーファイルに完全な型定義が必要です。

他のヒント

port_t 構造の内部データを非表示にする場合は、標準ライブラリが FILE オブジェクトを処理する方法などの手法を使用できます。クライアントコードは FILE * アイテムのみを処理するため、実際には FILE 構造にあるものについての知識は必要ありません(実際、そうすることはできません)。このメソッドの欠点は、クライアントコードがそのタイプの変数を単純に宣言できないことです。変数へのポインターしか持てないため、APIを使用してオブジェクトを作成および破棄し、 all オブジェクトの使用には、何らかのAPIを使用する必要があります。

これの利点は、 port_t オブジェクトの使用方法に対するすっきりとしたインターフェイスがあり、プライベートなものをプライベートに保つことができることです(非プライベートなものにはクライアントのゲッター/セッター関数が必要です)アクセスします)。

CライブラリでのFILE I / Oの処理方法と同じです。

私が使用する一般的なソリューション:

/* port.h */
typedef struct port_t *port_p;

/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};

関数インターフェースでport_pを使用します。 port.hにも特別なmalloc(および無料)ラッパーを作成する必要があります。

port_p portAlloc(/*perhaps some initialisation args */);
portFree(port_p);

別の方法をお勧めします:

/* port.h */
#ifndef _PORT_H
#define _PORT_H
typedef struct /* Define the struct in the header */
{
    unsigned int port_id;
    char name;
}port_t;
void store_port_t(port_t);/*Prototype*/
#endif

/* port.c */
#include "port.h"
static port_t my_hidden_port; /* Here you can hide whatever you want */
void store_port_t(port_t hide_this)
{
    my_hidden_port = hide_this;
}

/* main.c */
#include <stdio.h>
#include "port.h"
int main(void)
{
    struct port_t ports;
    /* Hide the data with next function*/
    store_port_t(ports);
    return 0;
}

通常、ヘッダーファイルで変数を定義するのは良くありません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top