I want to hide the struct define, so I define struct in the source file, like this :
//a.c
#include "a.h"
struct a_s
{
int a;
int b;
};
int func(a_t *a)
{
printf("%d\n", a->a);
return 0;
}
and I declare the struct in the header file, like this:
//a.h
#ifndef TEST
#define TEST
#include <stdio.h>
#include <stddef.h>
typedef struct a_s a_t;
#endif
Then I use the struct a_t
int main.c file, like this:
#include "stddef.h"
#include "a.h"
int main()
{
a_t a;
a.a =2;
func(&a);
return 0;
}
But when I compile the main.c by gcc -c main.c
, it failed by
main.c: In function ‘main’:
main.c:7:15: error: storage size of ‘a’ isn’t known
struct a_s a;
Why is this failing?
If you instantiate an object A a, the linker searches for the definition of A in order for the compiler to know how much memory it needs to allocate. It searches a.h and finds a typedef but no declaration, and so the error is saying that it doesn't know A's size.
If the purpose of the program is to hide the declarations (and definitions) from the users, you will need to use A *a, as this says to the compiler "there is a type A, and memory for it will be stored beginning at this memory location" and so doesn't need any information about the size or layout of the data until runtime where memory should be dynamically allocated and freed.
This approach allows the developers to expose an interface to users, without the users knowing any specifics on how data is structured and allowing the software to be updated and data structures modified all while keeping the outward facing headers the same (and keeping tests passing).