cstructdefinitionopaque-types

Opaque datatypes and structures in c


I have a very simple question. If I have a source code file like this:

#include<stdio.h>
#include"example.h"


struct mystructure{
    //Data Variables
    int a;
};

int main(){
   mystructure somename;
   somename.a = 1;
   
   printf("%d\n", somename.a);
    return 0;
}

With a header file like this:

#ifndef EXAMPLE_HEADER_H
#define EXAMPLE_HEADER_H

// Opaque declaration.
struct mystructure;
typedef struct mystructure mystructure;

#endif

The code will compile fine. I could also define the structure in the header file and it will compile fine.

However, if I define the structure in a different source code file and attempt to compile it with the main source code file it will keep throwing errors about forward declarations.

Is there a way to define a structure in a source code file give it a typedef in a header file and use it elsewhere in other source files?

I have been doing this awhile now by defining the structure in the header file, but I would like to know how to do this in a more opaque way.


Solution

  • To perform this declaration and statement

    mystructure somename;
    somename.a = 1;
    

    the compiler needs to know the complete definition of the structure struct mystructure. For instance it needs to know how much memory to allocate for the object somename and whether the structure has the data member a.

    So the definition of the structure must be visible in the module with main where these declaration and statement are present.

    To hide the structure definition you could declare a pointer of the type struct mystructure * and call functions to initialize this pointer and data members of the pointed object. The corresponding functions must know the structure definition.