开发者

Problem when compiling C++ code with Xcode

开发者 https://www.devze.com 2023-02-14 04:05 出处:网络
I was trying to compile some C++ code in Xcode and I got this error: Undefined symbols: \"Editorial::sm_nTotalEditorials\", referenced from:

I was trying to compile some C++ code in Xcode and I got this error:

Undefined symbols:
  "Editorial::sm_nTotalEditorials", referenced from:
      Editorial::AskTotal()     in editorial.o
      Editorial::~Editorial()in editorial.o
      Editorial::~Editorial()in editorial.o

The list follows with two more entries for the destructor and four more entries for the constructor (which I believe are the only functions in which I use sm_nTotalEditorials). I attach the definition of the variable and the functions in which I use it.

class Editorial
{
private:
     static int         sm_nTotalEditorials;
     ...
}

int Editorial::AskTotal() {return sm_nTotalEditorials;}

Editorial::~Editorial()
{
    if (!m_pPrev) sm_pFirstEditorial=m_pNext;
    if (m_pPrev) (*m_pPrev).SetContext((*m_pPrev).AskPrev(),m_pNext);
    if (m_pNext) (*m_pNext).SetContext(m_pPrev,(*m_pNext).AskNext());
    sm_nTotalEditorials--;
}

Then it prints similar error with the other 3 static private variables I'm using. I must be messing things up with static usage. This is my first C++ code, so I apologize for any bad syntax or if the question is too silly; I tried searching the internet but the error printed by Xcode is quite ambiguous and according to the tutorials I've seen, I'm using everything as it should be used. Also, the code is quite long to print all of it, and I pasted the par开发者_如何学Cts where I think the mistake should be, but again I am not sure of that either.


In C++, creating a static data member for a class is a two-step process. First, you have to declare the variable, which you've done here. However, you also have to define it somewhere so that the compiler knows where to put the storage space for the variable. Typically, this is done in the .cpp file for the class. In the .cpp file, try adding this line:

int Editorial::sm_nTotalEditorials = 0;

This gives the compiler the definition that it needs, and so you won't get any more linker errors complaining about the missing definition. You will also probably want to do this for the other static data members as well.

Note that when making these sorts of definitions you do not repeat the static keyword; that would give the static field static linkage, which won't resolve the problem.


Is it compiling as c++ code? I remember reading that the file will need a .mm extension to distinguish it from obj-c. There is also a file type drop down on the "Get Info" page for the file in Xcode.

0

精彩评论

暂无评论...
验证码 换一张
取 消