未定义的符号:符号引用错误。没有输出写入main

时间:2012-12-14 23:07:13

标签: c++ g++ undefined symbols

有以下计划:

#include <iostream>
#include <string>

using namespace std;

class Record
{
public:
    static Record* GetInstance(string name);
void printName();
private:
Record(string name);
string name_;
static Record *record;
};

Record::Record(string name)
:name_(name)
{
}

Record*
Record::GetInstance(string name)
{
if(record == NULL) {
    record = new Record(name);
}
return record;
}

void
Record::printName()
{
cout << name_ << endl;
}

int main()
{
Record* record1 = Record::GetInstance("sellers");
record1->printName();
Record* record2 = Record::GetInstance("customers");
record2->printName();   
}

我正在编译和链接:
    g ++ -g -c -Wall main.cpp
    g ++ -g -Wall main.o -o main

编译完成且没有错误(第一个命令)。但链接给出了这个错误:

Undefined                       first referenced    
 symbol                             in file    
Record::record                      main.o    
ld: fatal: Symbol referencing errors. No output written to main    
collect2: ld returned 1 exit status    

想知道如何纠正这个问题。

1 个答案:

答案 0 :(得分:2)

您需要在某处定义变量,即

Record *Record::record;