[Solved] How to create a file containing struct [closed]


Your problem “I am guessing” is the structure defintion

typedef struct test {
    int a;
};

This is not just a structure definition, but a type definition and it’s missing the type name, it can be fixed like this

typedef struct test {
    int a;
} MyTestStruct;

or simply remove the typedef and just use struct test to declare instances of it.

Also, if you intend to access it’s members then you must provide a definition in the same compilation unit where you access it’s members, in this case in the “main” file as you called it.

If you want to hide the members (make it an opaque structure), try like this

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__ */

And you would then have

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);
}

This technique is actually very elegant and has many advantages, the most important being that you can be sure that the structure is used correctly since no one can set the values directly and hence no one can set invalid/incorrect values. And also, if some of it’s members are allocated dynamically using malloc() you can ensure that they are freed when the user calls _destroy() on the pointer. You can control the range of values that you consider are appropriate, and avoid buffer overflows in cases where it applies.

4

solved How to create a file containing struct [closed]