Amir Saniyan
Amir Saniyan

Reputation: 13759

How to define and use a struct without full struct definition in header?

For controling struct members and force programmers to use getter/setter functions, I want to write code like below pattern:

/* Header file: point.h */
...
/* define a struct without full struct definition. */
struct point;

/* getter/setter functions. */
int point_get_x(const struct point* pt);
void point_set_x(struct point* pt, int x);
...

//--------------------------------------------

/* Source file: point.c */
struct point
{
  int x, y;
};

int point_get_x(const struct point* pt) {return pt->x; }

void point_set_x(struct point* pt, int x) {pt->x = x;}

//--------------------------------------------

/* Any source file: eg. main.c */

#include "point.h"
int main()
{
  struct point pt;

  // Good: cannot access struct members directly.
  // He/She should use getter/setter functions.
  //pt.x = 0;

  point_set_x(&pt, 0);
}

But this code does not compile with MSVC++ 2010.

Which changes should I do for compiling?

Note: I use ANSI-C (C89) standard, Not C99 or C++.

Upvotes: 0

Views: 2543

Answers (2)

  point pt;

The name of the type is struct point. You have to use the whole thing every time, or you need to typedef it.*

I.e. you should write

  struct point pt;

there in main.


You are probably thinking of FILE* and things like it from the standard library and want to duplicate that behavior. To do that use

struct s_point
typedef struct s_point point;

in the header. (There are shorter ways to write that, but I want to avoid confusion.) This declares a type named struct s_point and assigns it an alias point.


(*) Notice that this differs from c++, where struct point declares a type called point which is a struct.

Upvotes: 3

Doug Currie
Doug Currie

Reputation: 41200

Create a make_point function in point.c to create the point; main.c doesn't know how big the structure is.

Also

typedef struct point point;

will support using point rather than struct point in declarations.

Upvotes: 5

Related Questions