Search code examples
c++eclipsesdl

Undefined reference to 'Class::StaticStructMember'


This code is meant to help in profiling game code - and I can't seem to get my head around why it isn't working. I'm getting the following error message: undefined reference to `ProfileSample::profileSamples', and another for each of the points at which I've used its members.

#ifndef PROFILER_HPP_
#define PROFILER_HPP_

#define MAXIMUM_PROFILE_SAMPLES 16

class ProfileSample {
private:
    int sampleIndex, parentIndex;
    static int previousSampleIndex;

    inline float getTime(void) {
        return ((float)SDL_GetTicks()) / 1000.0f;
    }

    static struct profileSamples {
        float start, duration;
        char *name;
    } profileSamples[MAXIMUM_PROFILE_SAMPLES];
public:
    ProfileSample(const char *name) {
        sampleIndex = 0;
        while(profileSamples[sampleIndex].name != NULL)
            sampleIndex ++;

        parentIndex = (sampleIndex > 1) ? previousSampleIndex : -1;
        previousSampleIndex = sampleIndex;
        profileSamples[sampleIndex].name = (char *)name;
        profileSamples[sampleIndex].start = getTime();
    }

    ~ProfileSample(void) {
        float end = getTime();
        profileSamples[sampleIndex].duration = (end - profileSamples[sampleIndex].start);
        if(parentIndex >= 0)
            profileSamples[parentIndex].start -= profileSamples[sampleIndex].duration;
        if(sampleIndex == 0)
            output();
    }

    static void output(void) {
        for(int i = 1; i < MAXIMUM_PROFILE_SAMPLES; i ++) {
            printf("\nName: %s"
                    "\nDuration: %f"
                    "\nOverall percentage: %f",
                    profileSamples[i].name,
                    profileSamples[i].duration,
                    (profileSamples[0].duration / 100) * profileSamples[i].duration);
        }
    }
};

#endif /* PROFILER_HPP_ */

Can anybody explain what I'm missing here? Go easy, I've only just left C for C++


Solution

  •  static struct profileSamples {
            float start, duration;
            char *name;
        } profileSamples[MAXIMUM_PROFILE_SAMPLES];
    

    You have just declared this static structure. You haven't actually initialised it.

    If you add

        struct ProfileSample::profileSamples  ProfileSample::profileSamples[16] = {};
    int ProfileSample::previousSampleIndex = 1;
    

    After the class declaration it will actually fix the issue.

    You can think about it as a 2nd step, which is filling the memory with actual data. The first is just describing that some memory will be used and what interpretation data will have.

    Hope that this, combined with issue marked in comments will help you understand what is going on.