Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined symbol: Symbol referencing errors. No output written to main

Have the following program:

#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();   
}

I am compiling and linking with:
g++ -g -c -Wall main.cpp
g++ -g -Wall main.o -o main

The compilation completes without error(1st command). But the linking is giving this error:

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    

Wondering how to correct this.

like image 794
Romonov Avatar asked Dec 20 '25 13:12

Romonov


1 Answers

You need to define the variable somewhere, i.e.

Record *Record::record;
like image 173
melpomene Avatar answered Dec 22 '25 03:12

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!