0

I got a MFC app that is writing a huge hierarichy of objects to disk. To make sense of what is being written I thought of logging all the calls to archive << via stream insertion and .write method by replacing those with macros

#pragma once
#ifndef LOGMAGIC
#define LOGMAGIC

    class LogTab
    {
    public:
        static int LogIndentCount;
        LogTab()
        {
            LogIndentCount++;
        }

        ~LogTab()
        {
            LogIndentCount--;
        }
    };

    #define ARINSERT(AR,OBJ) TRACE( "%*s %s\n", LogTab::LogIndentCount, #OBJ); AR << OBJ;
    #define ARWRITE(AR,OBJ,SIZE) TRACE("%*s %s\n", LogTab::LogIndentCount, #OBJ); AR.write(OBJ, SIZE);
#endif

So I created above snippet of code and put it in stdafx.h but I'm getting the following error:

Error 1 error LNK2001: unresolved external symbol "public: static int LogTab::LogIndentCount" (?LogIndentCount@LogTab@@2HA)

What am I doing wrong? Is there a better way to achieve what I am doing?

Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
  • possible duplicate of [C++: undefined reference to static class member](http://stackoverflow.com/questions/272900/c-undefined-reference-to-static-class-member) – Flexo Aug 22 '11 at 11:12

2 Answers2

2

You have to define LogTab::LogIndentCount in any one of the .cpp files as,

#include"LogTab.h"
//...
int LogTab::LogIndentCount = 0;

[As a side note, if it's a multi threaded system which is using this class then you may think of making LogIndentCount synchronized (thread safe)]

iammilind
  • 68,093
  • 33
  • 169
  • 336
0

A static variable must be explicitly initialized.

log0
  • 10,489
  • 4
  • 28
  • 62
linc
  • 11
  • 3
  • Welcome to stackoverflow. I think your answer is on the right lines here, but it's not very clear. Example code, a link to another question (this question is a FAQ) or a more detailed explanation would be good. – Flexo Aug 22 '11 at 11:09