Search code examples
c++structglobal-variablesdynamic-allocation

Global dynamically allocated struct in c++


I'm having problems trying to use an array of structs which doesn't have an initial size. How do I do this? This is my struct:

struct carbon {
    double temp;
    double mass;
    rowvec::fixed<3> position;      
    rowvec::fixed<3> velocity;
    rowvec::fixed<3> force;
} *atom;

During my program I'm allocating size of the struct array like this:

  atom = new carbon[PARTICLE_NUM];

The problem is how I then use this struct in other files. I've created a header file and put this in it

extern struct carbon *atom;

But it comes up with this error:

setup_pos.cpp:19: error: invalid use of incomplete type ‘struct carbon’
system_setup_distances.h:18: error: forward declaration of ‘struct carbon’

I know I shouldn't be using global variables, but I just want to test this out first. Thanks in advance for the help.


Solution

  • The source file where you use atom needs the full definition of the carbon structure.

    Put the structure together with the external in the same header file, like this:

    struct carbon {
        double temp;
        double mass;
        rowvec::fixed<3> position;      
        rowvec::fixed<3> velocity;
        rowvec::fixed<3> force;
    };
    
    extern struct carbon *atom;
    

    The define the variable atom in one of your source files:

    struct carbon *atom = 0;
    

    Now, whenever you need to access atom, include the header file where the structure and the extern declaration is, and it should work.

    PS. Instead of having the atom variable in the global namespace, you could put it in its own namespace:

    namespace some_clever_name
    {
        struct carbon { ... };
        extern carbon *atom;
    }
    

    And put this in a source file:

    some_clever_name::carbon *some_clever_name::atom = 0;