Is it possible to make a library of a function.c where in the function, I can pass and return struct (defined in the same function.c file) ? Or do I need to make a separate library for struct ?
1 Answer
As others have alluded to in the comments, there are a few approaches:
Place struct definition in header files
lib.h
struct data {
...
}
void write_data(struct data *write);
void read_data(struct data *read);
lib.c
void write_data(struct data *write)
{
...
}
void read_data(struct data *read)
{
...
}
user.c
#include "lib.h"
void user(void)
{
struct data something;
read_data(&something);
write_data(&something);
}
This method is probably one of the most common, where you define the struct inside a header file which is included by the user of the library.
Provide opaque interface to user
lib.h
#define STRUCT_SIZE 100
void write_data(void *write);
void read_data(void *read);
lib.c
struct data {
...
}
void write_data(void *write)
{
struct data *write_struct;
write_struct = (struct data *)write;
...
}
void read_data(void *read)
{
struct data *read_struct;
read_struct = (struct data *)read;
...
}
user.c
#include "lib.h"
void user(void)
{
void *something;
something = malloc(STRUCT_SIZE);
read_data(something);
write_data(something);
}
This isn't quite as common as the first option, but still used from time to time. Generally, this is defined as an "external" or "opaque" struct in the library header (rather than defining a raw size). Inside the lib.c, an "internal" version of the struct is defined, which makes it more difficult for the user to use your underlying data structures.
Blind faith (not recommended)
lib.h
void write_data(void *write);
void read_data(void *read);
lib.c
struct data {
...
}
void write_data(void *write)
{
struct data *write_struct;
write_struct = (struct data *)write;
...
}
void read_data(void *read)
{
struct data *read_struct;
read_struct = (struct data *)read;
...
}
user.c
#include "lib.h"
// copy struct definition from lib.c.
// struct could keep the name 'data', but is renamed here to illustrate a point
// this is very dangerous and not recommended, as both structs must agree or things may not work
struct better_data {
...
}
void user(void)
{
struct better_data something;
read_data((void *)&something);
write_data((void *)&something);
}
I would not use this method in any situation, but I'm including it for illustrative purposes. This just shows that there isn't anything special about a structs, they are just memory. If two people agree on how to interpret the chunk of memory, things work. The purpose of placing the struct definition in the header file is to make it easy for people to share how to interpret the memory.
structin a header file made available with#include.struct's detail from the caller, but then you would need to provide functions to set/get its members.