Search code examples
c++cstructcompilationcompiler-construction

Including struct and compilation in c/c++


I noticed that when compiling and linking code that includes a struct in a header file, the struct declaration is actually needed only for compiling. Say I have a struct.h file, I can replace it with an empty file between compiling and linking without any problem.

My question is : what exactly is doing the compiler ? I guess there must be a copy of the struct full declaration in each .o file using the structure and I wonder how it makes sure that it is always the same struct.

Bonus question : is there a way to redefine the struct before linking ?


Solution

  • There are multiple aspects that I think are confusing you. Fundamentally, structs are merely a way to map multiple related variables together in a block of memory. So if you have a struct like:

    struct x {
        int a;
        int b;
    }
    

    And then you use that struct, internally the compiler is really creating a memory spot for for the entire structure. How big it is depends on the system, compiler, etc, but lets say an int is 4 bytes long (32-bits). It's often the case that what the compiler is doing when you access myvar.b its really referencing 4 bytes into the memory location where myvar is stored.

    But this is all done at compilation time where the compiler converts your C (or C++) code to an object file. It doesn't actually store the struct itself into the object file, only the offsets it needs to access the memory portions. Thus, linking doesn't require knowledge of the struct at all, which is why if you remove the struct from your .h during linking nothing changes: because the linker doesn't even read that file.