2016-11-11 15 views
1

私は2つのヘッダファイル、与える構造体の複数の名前

A.h

struct A { ... }; 
function declarations which use A 

B.h

function declarations which use the struct A here, and have functions which also use A. 
However, I want to call "A" B here. How can I do this? I want all the 
functions in here use 
struct B, which I want to be exactly the same as struct A since 

を行う私が "欲しい" ものの例を持っていますが、定義を使用していますおそらく、間違ったやりかたのやり方です:(注意してください、それは私が望む方法では完全に動作しますが、私はこの目的のために定義を使用するべきではないと思います。おそらくab Etterの物事を行う方法)

A.h

#ifndef A_H 
#define A_H 

struct A {int x;}; 

void A_DoSomething(struct A* a); 

#endif 

B.h

#ifndef B_H 
#define B_H 

#include "A.h" 

#define B A 

void B_DoSomething(struct* B b) { A_DoSomething(b); } 

#endif 

そう定義し使用しなくても、私がやりたいする方法はありますか?私はコードを再利用できるようにこれをやりたいつまり、Aはリンクされたリスト、Bはスタックです。リンクされたリストから私のスタックデータ構造を完全に定義することができます。

EDIT:だから、基本的にはBとAは同じですが、私のBhの/ BCファイル、およびBhのを使用して、任意のファイルに対して、私はちょうど構造を呼びたい「B」ではなく、私が使用する「」

+1

「を与えます構造体の複数の名前 "...' typedef'? – yano

+0

これは私にとっては難読化しているようです。あなたが解決しようとしている実際の問題は何ですか?なぜ彼らは同じ名前を持つことができないのですか? – Lundin

答えて

3

typedefと3つのhファイルを使用して共通データ構造をABから分離します。

MyNode.h:ような何か

#ifndef MyNode_H 
#define MyNode_H 

typedef struct Node 
{ 
    void *data; 
    struct Node *next; 
} Node; 

#endif 

A.h:

#ifndef A_H 
#define A_H 

#include "MyNode.h" 

typedef Node A; 

/* Declare functions for implementing a linked list using type A */ 

#endif 

B.h:

#ifndef B_H 
#define B_H 

#include "MyNode.h" 

typedef Node B; 

/* Declare functions for implementing a stack using type B */ 

#endif 

のmain.c:

#include <stdio.h> 
#include "A.h" 
#include "B.h" 

int main(void) { 
    /* Here A and B can be used as types, example: */ 
    A list = {NULL, NULL}; 
    B stack = {NULL, NULL}; 


    return 0; 
} 
関連する問題