2015-12-24 45 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 –

相关问题