Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c typedef(ed) opaque pointer

I've defined an opaque structure and related APIs like this:

typedef struct foo foo;
foo *create_foo(...);
delete_foo(foo *f);

I am not able to define the structure in my c file. Gives redefinition error.

typedef struct foo {
   int implementation;
}foo;

I am able to use foo in c file without typedef but I want the typedef (i.e. use it directly as foo*). Is there a way?

like image 802
Manish Avatar asked Mar 14 '11 13:03

Manish


People also ask

What is an opaque pointer in C?

In computer programming, an opaque pointer is a special case of an opaque data type, a data type declared to be a pointer to a record or data structure of some unspecified type. Opaque pointers are present in several programming languages including Ada, C, C++, D and Modula-2.

What is a typedef pointer?

The typedef may be used in declaration of a number of pointers of the same type. It does not change the type, it only creates a synonym, i.e., another name for the same type as illustrated below. typedef float* FP; // Now FP represents float* float x,y,z; FP px =&x, py = &y, pz = &z ; // Use of FP.

What is opaque structure?

In computer science, an opaque data type is a data type whose concrete data structure is not defined in an interface. This enforces information hiding, since its values can only be manipulated by calling subroutines that have access to the missing information.


1 Answers

You already have the typedef in your header, so include that and define struct foo in the implementation without the typedef.

foo.h:

typedef struct foo foo;
foo *create_foo(...);
delete_foo(foo *f);

foo.c:

#include <foo.h>

struct foo { int implementation; };
/* etc. */
like image 68
Fred Foo Avatar answered Sep 23 '22 05:09

Fred Foo