Struct Inheritance in C - c

Can I inherit a structure in C? If yes, how?

The closest you can get is the fairly common idiom:
typedef struct
{
// base members
} Base;
typedef struct
{
Base base;
// derived members
} Derived;
As Derived starts with a copy of Base, you can do this:
Base *b = (Base *)d;
Where d is an instance of Derived. So they are kind of polymorphic. But having virtual methods is another challenge - to do that, you'd need to have the equivalent of a vtable pointer in Base, containing function pointers to functions that accept Base as their first argument (which you could name this).
By which point, you may as well use C++!

C has no explicit concept of inheritance, unlike C++. However, you can reuse a structure in another structure:
typedef struct {
char name[NAMESIZE];
char sex;
} Person;
typedef struct {
Person person;
char job[JOBSIZE];
} Employee;
typedef struct {
Person person;
char booktitle[TITLESIZE];
} LiteraryCharacter;

I like and used the idea of Typesafe inheritance in C.
For example:
struct Animal
{
int weight;
};
struct Felidae
{
union {
struct Animal animal;
} base;
int furLength;
};
struct Leopard
{
union {
struct Animal animal;
struct Felidae felidae;
} base;
int dotCounter;
};
Usage:
struct Leopard leopard;
leopard.base.animal.weight = 44;
leopard.base.felidae.furLength = 2;
leopard.dotCounter = 99;

If your compiler supports anonymous structs, you can do this:
typedef struct Base
{
// base members
} Base_t;
typedef struct
{
struct Base; //anonymous struct
// derived members
} Derived_t;
This way, base stuct members can be acessed directly, which is nicer.

If you want to use some gcc magic (that I would assume would work with Microsoft's C compiler) you can do something like:
struct A
{
int member1;
};
struct B
{
struct A;
int member2;
}
With gcc you can compile this with -fms-extensions (Allows for unnamed struct members like Microsofts compiler does). This is similar to the solution given by Daniel Earwicker except that it allows you to access memeber1 on a struct B instance. i.e B.member1 instead of B.A.member1.
This is probably not the most portable approach and will not work if using a C++ compiler (different language semantics mean that it is redeclaring/defining struct A instead of instantiating it).
If however you live in the gcc/C land only it will work and do exactly what you want.

This works compiling with -fms-extensions
Diagram image
main.c
#include "AbstractProduct.h"
#include "Book.h"
#include "Product.h"
#include "TravelGuide.h"
/***********************/
int main() {
Product p = Product_new();
p.set_id(&p, 2);
p.set_name(&p, "name2");
p.set_description(&p, "description2");
p.set_price(&p, 2000);
p.display(&p);
TravelGuide tg = TravelGuide_new();
tg.set_id(&tg, 1);
tg.set_name(&tg, "name1");
tg.set_description(&tg, "description1");
tg.set_price(&tg, 1000);
tg.set_isbn(&tg, "isbn1");
tg.set_author(&tg, "author1");
tg.set_title(&tg, "title1");
tg.set_country(&tg, "country1");
tg.display(&tg);
}
AbstractProduct.c
#include "AbstractProduct.h"
/*-------------------------------*/
static void set_id(AbstractProduct *this, int id) {
this->id = id;
}
/*-------------------------------*/
static void set_name(AbstractProduct *this, char *name) {
strcpy(this->name, name);
}
/*-------------------------------*/
static void set_description(AbstractProduct *this, char *description) {
strcpy(this->description, description);
}
/*-------------------------------*/
static int get_id(AbstractProduct *this) {
return this->id;
}
/*-------------------------------*/
static char *get_name(AbstractProduct *this) {
return this->name;
}
/*-------------------------------*/
static char *get_description(AbstractProduct *this) {
return this->description;
}
/*-------------------------------*/
static void display(AbstractProduct *this) {
printf("-AbstractProduct- \n");
printf("id: %d\n", this->get_id(this));
printf("name: %s\n", this->get_name(this));
printf("description: %s\n", this->get_description(this));
printf("\n");
}
/*-------------------------------*/
void AbstractProduct_init(AbstractProduct *obj) {
obj->set_id = set_id;
obj->set_name = set_name;
obj->set_description = set_description;
obj->get_id = get_id;
obj->get_name = get_name;
obj->get_description = get_description;
obj->display = display;
}
/*-------------------------------*/
AbstractProduct AbstractProduct_new() {
AbstractProduct aux;
AbstractProduct_init(&aux);
return aux;
}
AbstractProduct.h
#ifndef AbstractProduct_H
#define AbstractProduct_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/***********************/
typedef struct AbstractProduct{
int id;
char name[1000];
char description[1000];
void (*set_id)();
void (*set_name)();
void (*set_description)();
int (*get_id)();
char *(*get_name)();
char *(*get_description)();
void (*display)();
} AbstractProduct;
AbstractProduct AbstractProduct_new();
void AbstractProduct_init(AbstractProduct *obj);
#endif
Book.c
#include "Book.h"
/*-------------------------------*/
static void set_isbn(Book *this, char *isbn) {
strcpy(this->isbn, isbn);
}
/*-------------------------------*/
static void set_author(Book *this, char *author) {
strcpy(this->author, author);
}
/*-------------------------------*/
static void set_title(Book *this, char *title) {
strcpy(this->title, title);
}
/*-------------------------------*/
static char *get_isbn(Book *this) {
return this->isbn;
}
/*-------------------------------*/
static char *get_author(Book *this) {
return this->author;
}
/*-------------------------------*/
static char *get_title(Book *this) {
return this->title;
}
/*-------------------------------*/
static void display(Book *this) {
Product p = Product_new();
p.display(this);
printf("-Book- \n");
printf("isbn: %s\n", this->get_isbn(this));
printf("author: %s\n", this->get_author(this));
printf("title: %s\n", this->get_title(this));
printf("\n");
}
/*-------------------------------*/
void Book_init(Book *obj) {
Product_init((Product*)obj);
obj->set_isbn = set_isbn;
obj->set_author = set_author;
obj->set_title = set_title;
obj->get_isbn = get_isbn;
obj->get_author = get_author;
obj->get_title = get_title;
obj->display = display;
}
/*-------------------------------*/
Book Book_new() {
Book aux;
Book_init(&aux);
return aux;
}
Book.h
#ifndef Book_H
#define Book_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "Product.h"
/***********************/
typedef struct Book{
Product;
char isbn[1000];
char author[1000];
char title[1000];
void (*set_isbn)();
void (*set_author)();
void (*set_title)();
char *(*get_isbn)();
char *(*get_author)();
char *(*get_title)();
// void (*display)();
} Book;
Book Book_new();
void Book_init(Book *obj);
#endif
Product.c
#include "Product.h"
/*-------------------------------*/
static void set_price(Product *this, double price) {
this->price = price;
}
/*-------------------------------*/
static double get_price(Product *this) {
return this->price;
}
/*-------------------------------*/
static void display(Product *this) {
AbstractProduct p = AbstractProduct_new();
p.display(this);
printf("-Product- \n");
printf("price: %f\n", this->get_price(this));
printf("\n");
}
/*-------------------------------*/
void Product_init(Product *obj) {
AbstractProduct_init((AbstractProduct*)obj);
obj->set_price = set_price;
obj->get_price = get_price;
obj->display = display;
}
/*-------------------------------*/
Product Product_new() {
Product aux;
Product_init(&aux);
return aux;
}
Product.h
#ifndef Product_H
#define Product_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "AbstractProduct.h"
/***********************/
typedef struct Product{
AbstractProduct;
double price;
void (*set_price)();
double (*get_price)();
// void (*display)();
} Product;
Product Product_new();
void Product_init(Product *obj);
#endif
TravelGuide.c
#include "TravelGuide.h"
/*-------------------------------*/
static void set_country(TravelGuide *this, char *country) {
strcpy(this->country, country);
}
/*-------------------------------*/
static char *get_country(TravelGuide *this) {
return this->country;
}
/*-------------------------------*/
static void display(TravelGuide *this) {
Book b = Book_new();
b.display(this);
printf("-TravelGuide- \n");
printf("country: %s\n", this->get_country(this));
printf("\n");
}
/*-------------------------------*/
void TravelGuide_init(TravelGuide *obj) {
Book_init((Book*)obj);
obj->set_country = set_country;
obj->get_country = get_country;
obj->f = obj->display;
obj->display = display;
}
/*-------------------------------*/
TravelGuide TravelGuide_new() {
TravelGuide aux;
TravelGuide_init(&aux);
return aux;
}
TravelGuide.h
#ifndef TravelGuide_H
#define TravelGuide_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "Book.h"
/***********************/
typedef struct TravelGuide{
Book;
char country[1000];
void (*f)();
void (*set_country)();
char *(*get_country)();
// void *(*display)();
} TravelGuide;
TravelGuide TravelGuide_new();
void TravelGuide_init(TravelGuide *obj);
#endif
Makefile
.PHONY: clean
define ANNOUNCE_BODY
***********************************************
************ start make **************
***********************************************
endef
all:
$(info $(ANNOUNCE_BODY))
clear;
if [ -f binary/main ]; then rm binary/main; fi;
# compiler
gcc $(INC) -c -fms-extensions main.c -o binary/main.o
gcc $(INC) -c -fms-extensions AbstractProduct.c -o binary/AbstractProduct.o
gcc $(INC) -c -fms-extensions Product.c -o binary/Product.o
gcc $(INC) -c -fms-extensions Book.c -o binary/Book.o
gcc $(INC) -c -fms-extensions TravelGuide.c -o binary/TravelGuide.o
# linker
gcc binary/main.o \
binary/AbstractProduct.o \
binary/Product.o \
binary/Book.o \
binary/TravelGuide.o \
-o \
binary/main

You can do the above mentioned
typedef struct
{
// base members
} Base;
typedef struct
{
Base base;
// derived members
} Derived;
But if you want to avoid pointer casting, you can use pointers to a union of Base and Derived.

A slight variation to the answer of anon (and others' similar). For one level deep inheritance one can do the following:
#define BASEFIELDS \
char name[NAMESIZE]; \
char sex
typedef struct {
BASEFIELDS;
} Person;
typedef struct {
BASEFIELDS;
char job[JOBSIZE];
} Employee;
typedef struct {
BASEFIELDS;
Employee *subordinate;
} Manager;
This way the functions accepting pointer to Person, will accept pointer to Employee or Manager (with casting), same as in other answers, but in this case the initialisation will be natural as well:
Employee e = {
.name = "...";
...
};
vs
# as in anon's answer
Employee e = {
.person.name = "...";
...
};
I believe this is how some popular projects do that (eg. libuv)
UPDATE: also there are some good examples of similar (but not the same) concept in libsdl events implementation using structs and unions.

C is not an object-oriented language and hence has no inheritance.

You can simulate it, but you can't really inherit.

No, you cant.
imo the best approach to OOP in C is using ADT.

No you cannot. C does not support the concept of inheritance.

Related

How to send to a function a variable that is in another module?

How can I send a pointer that´s in another module to a new module?
Hello, I´m just starting a Programming Proyect in c of a game for class. This game contains a struct called game that also contains differents types data like Players ir Objects. Those structs are identified by a long Id, classified so that the objects have an Id between #0 and #100 for example.
To make it easier I´ve been creating a function "what_id" that recibing just an Id it returns a pointer to the struct that corresponds to it. I know how by sending the 'game' struct where are contained all the ids, and an Id, return the variable, but there´re modules that do not use in any case that big 'game' variable, for example player.c.
How can I send 'game' to this function without having it?
typedef struct _Game{
Player* player[MAX_PLAYERS + 1];
Object* object[MAX_OBJECTS + 1];
Space* spaces[MAX_SPACES + 1];
T_Command last_cmd;
} Game;
typedef struct _Object{
Id id;
char name[MAX_SPACES];
}
void* what_id(Game* game, Id id){
if(id == NO_ID) return ERROR;
if(0 <id<=MAX_SPACES){
return what_space(game->space, id);
}else if(MAX_SPACES<id<=(MAX_OBJECTS+MAX_SPACES)){
return what_object(game->object, id);
}else if((MAX_OBJECTS+MAX_SPACES<id<(MAX_PLAYERS+MAX_OBJECTS+MAX_SPACES)){
return what_player(game->player, id);
}else {
fprinf(stderr,"Id asigment max stacked.";
return ERROR;
}
}
Space* what_space(const Space* space, Id id){
int i;
for(i=0;i<MAX_SPACES;i++){
if(space[i]->id == id)return space[i];
}
fprintf(stderr, "Error no space_id %d founded", id);
return ERROR;
}
It's not clear what you mean by "module", or where Game is going to come from. If by modules you mean separate sources files that produce separate object files, there are generally two ways to do this.
The first is to declare a global variable and import it as an extern:
file1.c:
// declare struct
typedef struct {
int value;
} Foo;
// declare global variable
Foo *globalfoo;
// declare external function from another module
void printfoo();
void main()
{
Foo foo;
foo.value = 3;
globalfoo = &foo;
printfoo();
}
file2.c:
#include <stdio.h>
// declare struct
typedef struct {
int value;
} Foo;
// declare variable from another module
extern Foo *globalfoo;
void printfoo()
{
printf("foo: %d\n", globalfoo->value);
}
The other way to do it is to pass it via a function argument:
file1.c:
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo);
void main()
{
Foo foo;
foo.value = 3;
printfoo(&foo);
}
file2.c:
#include <stdio.h>
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo)
{
printf("foo: %d\n", foo->value);
}
You can avoid re-declaring structs and functions in multiple source files by putting them in a header file and #including it:
myproject.h:
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo);
file1.c:
#include <myproject.h>
void main()
{
Foo foo;
foo.value = 3;
printfoo(&foo);
}
file2.c:
#include <myproject.h>
#include <stdio.h>
void printfoo(Foo *foo)
{
printf("foo: %d\n", foo->value);
}

Is this a correct/safe way to define and use "interfaces" in pure C

for the past few months I've been trying to code in pure C and avoid C++ as much as I can (for personal reasons, C++ is a nice language in deed), but once in a while there comes situations where I miss some concepts that I used to be using a lot back when I coded in C++, which there is no obvious equivalent in C for them, one of those concepts being "Interface". so after a few hours of research I came up with this solution but I'm afraid that my code might go wrong sometime in the future. Below is the sample code of what I want to do:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef int (*on_affected_cb) (const char *msg);
typedef struct affectee_t affectee_t;
typedef struct type_a_t type_a_t;
typedef struct type_b_t type_b_t;
typedef struct type_c_t type_c_t;
typedef struct owner_t owner_t;
//******************************************************************************
struct affectee_t{ //interface
on_affected_cb on_affected;
};
void affectee_notify(affectee_t* self, const char* msg){
self->on_affected(msg);
}
//******************************************************************************
struct type_a_t{ //implementor a
affectee_t affectee;
int num;
};
static int type_a_on_affected (const char *msg){
printf("this is type a reading msg: %s\n", msg);
return 1000;
}
void type_a_init(type_a_t* self){
self->num = 0;
self->affectee.on_affected = type_a_on_affected;
}
//******************************************************************************
struct type_b_t{ //implementor b
affectee_t affectee;
char name[128];
};
static int type_b_on_affected (const char *msg){
printf("this is type b reading msg: %s\n", msg);
return 2000;
}
void type_b_init(type_b_t* self){
memset(self->name, 0, sizeof(self->name));
self->affectee.on_affected = type_b_on_affected;
}
//******************************************************************************
struct owner_t{ // ordinary struct/class
type_a_t ta;
type_b_t tb;
};
void owner_init(owner_t* self){
type_a_init(&self->ta);
type_b_init(&self->tb);
}
void owner_notify(owner_t* self){
const char msg[] = "what the f...!";
affectee_notify((affectee_t*)&self->ta, msg); //<- pointer casting!!!
affectee_notify((affectee_t*)&self->tb, msg); //<- same here
}
//******************************************************************************
int main(int argc, char **argv){
owner_t owner;
owner_init(&owner);
owner_notify(&owner);
}

Forward declaration C

I have 2 header files api.h and impl.h
api.h is visible to outside files and will be included in other ".c" files. So api.h includes impl.h
api.h defines 2 structures
typedef struct
{
uint32_t att;
union
{
struct
{
void* buffer;
size_t length;
} x;
struct
{
int a, b;
} v;
} content;
}dummy;
and impl.h has some other structures and function def which uses this structure.
I tried forward declaration but it doesn't help me .
Please help .
Actually, your dummy is not a structure, but a typedef to an unnamed structure. Try naming the structure, you can then forward-declare it:
typedef struct sdummy dummy; // forward declaration
void foo(dummy *);
struct sdummy { ... }; // definition
Either reorder your code in api.h so the type declaration precedes the #include "impl.h" or give your (currently anonymous) structure itself a name like dummy, dummy_, dummy_s so you can add a forward declaration
typedef struct dummy_ dummy;
to impl.h.
If you want to hide the details of your struct then you have to define it in some .c file, let's say impl.c, so that it has internal linkage to that compilation unit. To use it you have to expose create, destroy, getter and setter functions. So a basic setup would look like this:
api.h with forward declaration for your struct
// forward declaration
typedef struct dummy* dummy_t;
// create / destroy / setter / getter (omitted)
dummy_t alloc_dummy();
void free_dummy(dummy_t);
void set_number(dummy_t, int);
void set_string(dummy_t, char*);
void print_dummy(dummy_t);
Then comes impl.c
#include "api.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct dummy {
int n;
char* s;
};
dummy_t alloc_dummy()
{
return malloc(sizeof(struct dummy));
}
void free_dummy(dummy_t dummy)
{
if(dummy) {
free(dummy->s);
free(dummy);
}
}
void set_number(dummy_t dummy, int n)
{
if(dummy) {
dummy->n = n;
}
}
void set_string(dummy_t dummy, char* s)
{
if(dummy && s) {
dummy->s = strdup(s);
}
}
void print_dummy(dummy_t dummy)
{
if(dummy) {
printf("%d, %s\n", dummy->n, dummy->s);
}
}
And finally the usage in some other C files, here main.c
#include "api.h"
int main(int argc, char** argv)
{
// struct dummy d; // error! type is unknown
// instead use the create function
dummy_t d = alloc_dummy();
// d->n = 1; // error! dereference of unknown type
// instead use the setter function
set_number(d, 1);
set_string(d, "Hello, world!");
print_dummy(d);
free_dummy(d);
return 0;
}
Ouput
1, Hello, world!

What is the data type of the name of a struct

If I wanted to make a function which takes the name of a struct as an argument, what would the method signature look like?
typedef struct Class{
} Class;
main()
{
Class *a = malloc(Class);
return instanceOf(a, Class);
}
What would the declaration of instanceOf look like?
You can't pass types to functions in C. However, you can simulate this behaviour using macros:
#define new_instance(t) (malloc(sizeof(t)))
Class *instance = new_instance(Class);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define type(x) #x
typedef struct Class{
char* type;
} Class;
Class *Class_new(){
Class *v;
v=(Class*)malloc(sizeof(Class));
v->type = "Class";
return v;
}
void Class_free(Class *a){
free(a);
}
int instanceOf(Class *a, const char* type){
return strcmp(a->type, type) == 0;
}
int main(){
Class *a = Class_new();
printf("%s\n", instanceOf(a, type(Class)) ? "YES" : "NO");
Class_free(a);
return 0;
}
// Encode and encapsulate the type within a nested structure when you create it.
struct struct_info
{
int type;
char name[32];
}
struct mystruct
{
struct struct_info;
}

Typecasting (or deference) void * to struct foo*

In api.h
typedef void* hidden_my_type;
void do_something(my_type x);
In core.c
struct _my_type
{
int a;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x; /*Don't understand is that correct way to do, as I'm getting segmentation fault error */
printf("Value: %d\n", x->a);
}
Other way I thought as,
struct *_my_type x = (struct _my_type *)malloc(sizeof(struct _my_type));
void_x = x
printf(Value: %d\n", x->a);
But still I'm getting seg-fault error.
ok here is the problem with void*....
e.g.
in core.c
void init_my_type(hidden_my_type a)
{
my_type *the_a = malloc(...);
a = the_a // <<<<<<<<<<<<<<<<<<<<<<<<<<<< is this correct?! a is void* and the_a // is original type
pthread_cond_init(&the_a->...);
.. (in short any other methods for init ..)
}
void my_type_destroy(my_hidden_type x)
{
my_type *the_x = x;
pthread_detroy(&the_x-> ...);
}
in main.c
test()
{
my_hidden_type x;
init_my_type(x);
....
my_type_detroy(x);
}
this it self should fail. as in main.c test function, x is void* ... init will allocate but in destroy I'm again passing void* .. which can be anything!
EDIT (Solved for me)
In api.h
typedef void* hidden_my_type;
void do_something(my_type x);
In core.c
struct _my_type
{
int a;
}
void init_hidden_type(hidden_my_type void_p_my_type)
{
struct _my_type *real_my_type = (struct _my_type *)malloc(sizeof(struct _my_type));
//--- Do init for your type ---
void_p_my_type = real_my_type;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x;
printf("Value: %d\n", x->a);
}
Version 0 — Critique of Question's Code
The posted code does not compile.
api.h
typedef void* hidden_my_type;
void do_something(my_type x);
This defines hidden_my_type but not the my_type that is passed to do_something(). Presumably, you intended:
typedef void *my_type;
void do_something(my_type x);
core.c
struct _my_type
{
int a;
}
As noted below too, there is a semi-colon missing after the structure definition.
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x;
printf("Value: %d\n", x->a);
}
You have the hidden_my_type vs my_type problem again. You have the * of the pointer where it cannot go; it must go after the struct _my_type. You probably intended something like:
void do_something(my_type void_x)
{
struct _my_type *x = void_x;
printf("Value: %d\n", x->a);
}
This is now syntactically correct (I think; I haven't actually run it past a compiler). You have not shown how it is used; indeed, since the user code has no way to generate a pointer to a valid structure, there is no way for this code to be used safely.
Your test code (unshown — why don't you show your test code) might look something like this:
#include "api.h"
int main(void)
{
my_type x = 0;
do_something(x);
return 0;
}
Alternatively, it might not have the = 0 initializer in place. Either way, your code is unable to function sanely, and a core dump is almost inevitable. When you hide the structure from the user, you have to provide them with a mechanism to get hold of a valid (pointer to) the structure, and you've not done that.
Version 1
This is a better way to do it, because it is more nearly type-safe:
api.h version 1
typedef struct _my_type *my_type;
void do_something(my_type x);
core.c version 1
#include "api.h"
struct _my_type
{
int a;
};
Note the added semi-colon, and the include of the api.h file.
void do_something(my_type x)
{
// Now you don't have to do casting here!
//struct *_my_type x = void_x; /*Don't understand is that correct way to do, as I'm getting segmentation fault error */
printf("Value: %d\n", x->a);
}
Version 2
Actually, we can debate the wisdom of hiding the pointer; I would prefer not to do so:
api.h version 2
#ifndef API_H_INCLUDED
#define API_H_INCLUDED
typedef struct my_type my_type;
extern void do_something(my_type *x);
extern my_type *my_type_initializer(void);
extern void my_type_release(my_type *x);
#endif /* API_H_INCLUDED */
core.c version 2
#include "api.h"
#include <stdio.h>
#include <stdlib.h>
struct my_type
{
int a;
};
void do_something(my_type *x)
{
printf("Value: %d\n", x->a);
}
my_type *my_type_initializer(void)
{
my_type *x = malloc(sizeof(*x));
x->a = 57; // More plausibly, this would be 0
return x;
}
void my_type_release(my_type *x)
{
free(x);
}
main.c
#include "api.h"
int main(void)
{
my_type *x = my_type_initializer();
do_something(x);
my_type_release(x);
return 0;
}
That's nice and clean. Of course, the user cannot allocate a struct my_type (only a pointer to it), so you need a function to allocate the structure for them. Think of the Standard C Library, and the FILE type, and fopen() to allocate and fclose() to release and fprintf() etc to manipulate the type. The my_type_initializer() is functioning as an analogue to fopen(), my_type_release() as an analogue to fclose(), and do_something() as an analogue to fprintf().
Jonathan, you beat me to an answer, but this may be helpful as well. Here, api.c contains the (private) implementation, and api.h provides the interface to be consumed by other code such as main.c.
// main.c: uses only the public interface to the private code
#include "api.h"
int main(int argc, char *argv[]) {
void *foo;
foo = create_foo("five", 5);
print_foo(foo);
delete_foo(foo);
}
// EOF main.c
// api.h: the public interface
#ifndef _api_h_
#define _api_h_
void *create_foo(char *name, int number);
void print_foo(void *foo);
void delete_foo(void *foo);
#endif // _api_h_
// api.c: the private implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// The real structure is private to the implementation.
typedef struct {
char name[20];
int number;
} real_struct;
// Create a new structure, initialize, return as ptr-to-void.
void *create_foo(char *name, int number) {
real_struct *s = malloc(sizeof(real_struct));
strcpy(s->name, name);
s->number = number;
return (void *) s;
}
// Print the data.
void print_foo(void *foo) {
real_struct *s = (real_struct *) foo;
printf("name: %s, number: %d\n", s->name, s->number);
}
// Release the memory.
void delete_foo(void *foo) {
free(foo);
}
// EOF api.c
This code should compile and run:
$ gcc -o foo main.c api.c
$ ./foo
name: five, number: 5

Resources