2015-12-24 69 views
-7

我想要控制類,結構體或其他文件。但是,當我創建它。我無法運行我的程序。這是我的計劃: main文件:如何創建一個包含結構的文件

#include <stdio.h> 
#include <stdlib.h> 
#include "testing.h" 

    int main(int argc, char** argv) { 
     struct test var; 
     var.a = 2; 
     return (EXIT_SUCCESS); 
    } 

文件頭的結構:

#ifndef TESTING_H 
#define TESTING_H 

    struct test x; 

#endif /* TESTING_H * 

和最後一個是文件中定義的結構:

typedef struct test { 
    int a; 
}; 

我沒有創造新的多少經驗文件。可能是我的問題是愚蠢的。希望大家幫助我。謝謝!

+0

請更具體地說明您的問題。 – Petr

+0

請先閱讀[問]頁面。 –

+1

@Petr,沒有涉及.cpp文件。看代碼,它是[tag:c]。 –

回答

1

你們的問題「我猜」是結構確定指標

typedef struct test { 
    int a; 
}; 

這不僅僅是一個結構定義,而是一種類型定義,它缺少的類型名稱,它可以是固定的這樣

typedef struct test { 
    int a; 
} MyTestStruct; 

或者乾脆刪除typedef,只需使用struct test聲明它的實例。另外,如果你打算訪問它的成員,那麼你必須在你訪問它的成員的同一個編譯單元中提供一個定義,在這種情況下,在你調用它的「main」文件中。

如果你想隱藏的成員(使其不透明結構),嘗試這樣

struct.h

#ifndef __STRUCT_H__ 
#define __STRUCT_H__ 
struct test; // Forward declaration 

struct test *struct_test_new(); 
int struct_test_get_a(const struct test *const test); 
void struct_test_set_a(struct test *test, int value); 
void struct_test_destroy(struct test *test); 

#endif /* __STRUCT_H__ */ 

然後,你將不得不

struct.c

#include "struct.h" 

// Define the structure now 
struct test { 
    int a; 
}; 

struct test * 
struct_test_new() 
{ 
    struct test *test; 
    test = malloc(sizeof(*test)); 
    if (test == NULL) 
     return NULL; 
    test->a = DEFAULT_A_VALUE; 
    return test; 
} 

int 
struct_test_get_a(const struct test *const test) 
{ 
    return test->a; 
} 

void 
struct_test_set_a(struct test *test, int value) 
{ 
    test->a = value; 
} 

void 
struct_test_destroy(struct test *test) 
{ 
    if (test == NULL) 
     return; 
    // Free all freeable members of `test' 
    free(test); 
} 

這種技術實際上非常優雅,並且有很多優點,最重要的是您可以確保結構使用正確,因爲沒有人可以直接設置值,因此沒有人可以設置無效/不正確的值。而且,如果某些成員是使用malloc()動態分配的,則可以確保在用戶在指針上調用_destroy()時釋放它們。您可以控制您認爲合適的值的範圍,並在適用的情況下避免緩衝區溢出。

+0

我只能用文件頭做,但我想用.c或.cpp文件來做更多的程序,那麼怎麼做呢?或者不能做它與struct? –

+0

我不明白,如果你想隱藏用戶的成員,你可以創建存取函數,例如'int struct_test_get_a(const struct test * const test){return test-> a;};你可以使用'struct_test_set_a(struct test * test,int value){test-> a = value;}'來設置它,然後使用指向結構實例的指針而不是實例 –

+0

可能是我的級別不夠理解你的代碼無論如何非常感謝我會努力達到你的水平D –

相關問題