Simone
Simone

Reputation: 129

How to use in main.c a structure defined in another .c file?

I declared a struct on a header file, let's take this as example:

//file.h
#ifndef FILE_H_INCLUDED
#define FILE_H_INCLUDED

typedef struct {
    int x;
    int y;
} Point;

#endif // FILE_H_INCLUDED

Then I defined that struct on another file, that contains prototypes of function that I will use on main.c:

//functions.c
#include "file.h"

Point p = {{1},{2}};

Now my question is, how can I use that struct on main.c? Would like to do something like:

//main.c
#include "file.h"

printf("Point x: %d", p.x);

Now, my real struct got 8 fields and it's an array of 40 elements, so it's 40 rows of code, and I would like to not put it in main.c, as I want it as clear as possible. I can't use global vars tho.

Upvotes: 0

Views: 129

Answers (2)

Massey101
Massey101

Reputation: 346

Try this:

// file.h
typedef struct {
    int x;
    int y;
} Point;
void setup_point(Point *);

// functions.c
#include "file.h"
void setup_point(Point * p) {
    p->x = 1;
    p->y = 2;
}

// main.c
#include "file.h"
int main() {
    Point p;
    setup_point(&p);
    printf("Point x: %d", p.x);
}

This is ideal as the logic for your struct is contained in a separate file and it does not use global variables.

Upvotes: 1

chux
chux

Reputation: 153456

Create a function the returns the address of p.

 //file.h
 Point *Point_p(void);

//functions.c
#include "file.h"
static Point p = {{1},{2}};
Point *Point_p(void) { return &p; }

//main.c
#include "file.h"
printf("Point x: %d", Point_p()->x);

Upvotes: 0

Related Questions