2016-01-04 58 views
0

因此,我將此代碼與一個結構和一堆函數結合在一起,並且我希望將這些函數(至少)放在一個單獨的.c文件中。但是,當我這樣做時,它不再識別我擁有的結構卡類型。我該怎麼辦?C - 要將類型struct的函數放在單獨的.c文件中

#include <stdlib.h> 
#include <stdio.h> 
#include <time.h> 

struct card { 
    int suit; 
    int value; 
}; 

const char *suitName(int suitNum) 
{ 
    switch (suitNum) { 
    case 1: return "spades"; 
    case 2: return "clubs"; 
    case 3: return "hearts"; 
    case 4: return "diamonds"; 
    } 

    return "(invalid suit)"; 
} 

struct card makeCard(int suit, int value) { 

    struct card tempCard; 
    tempCard.suit = suit; 
    tempCard.value = value; 

    return tempCard; 
} 

struct card *createDeck() 
{ 
    const size_t count = 52; 
    struct card *deck; 


    /* Allocate new deck of 'count' cards. */ 
    deck = malloc(count * sizeof deck[0]); 
    if (!deck) { 
     fprintf(stderr, "createDeck(): Out of memory!\n"); 
     exit(EXIT_FAILURE); 
    } 
    int i = 0; 
    struct card *deckArrayPtr = deck; 
    for (int suit = 1; suit < 5; suit++) 
    { 
     { 
      for (int value = 1; value < 14; value++) { 
       deck[i] = makeCard(suit, value); 
       i++; 
      } 
     } 
    } 
    return deck; 
} 

void shuffleDeck(struct card *deck) { 
    int cardSwitch1, cardSwitch2; 
    struct card temp; 
    cardSwitch1 = (rand() % 52); 
    cardSwitch2 = (rand() % 52); 
    temp = deck[cardSwitch1]; 
    deck[cardSwitch1] = deck[cardSwitch2]; 
    deck[cardSwitch2] = temp; 
} 


int main() 
{ 
    srand((unsigned int)time(NULL)); //initializing srand 

    struct card *deckAr = createDeck(); //creating the struct card deck array 

    for (int i = 0; i < 5000; i++) 
    { 
     shuffleDeck(deckAr); 
    } 
    for (int a = 0; a < 52; a++) { 
     //printf("%d of %s\n", deckAr[a].value, suitName(deckAr[a].suit)); 
     printf("%d of %s\n", deckAr[a].value, suitName(deckAr[a].suit)); 
    } 
    return 0; 
} 
+1

寫,你把你的'struct' .h文件。將此文件包含在.c文件中。 – Rabbid76

回答

2

寫在那裏你declerate你的類型和函數原型

mytypes.h

struct card { 
    int suit; 
    int value; 
}; 

const char *suitName(int suitNum); 
struct card makeCard(int suit, int value); 
... 

頭文件寫在那裏你實現你的功能.c文件(包括你的頭文件)

myfunc.c

#include "mytypes.h" 

const char *suitName(int suitNum) 
{ 
    ... 
} 
... 

最後,對於你的主程序文件

的main.c

#include "mytypes.h" 

int main() 
{ 
    ... 
} 
+0

謝謝,我以爲我以某種方式需要原型的結構,但無法找到任何網上有關它。也許應該是我自己想出來的。 ^^」 –