Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why could I not find the class in preprocessor?

This might be very naive, but I am quite confused about the preprocessor of cpp: I defined a header file-- Node.h:

#ifndef NODE_H_
#define NODE_H_

#include<iostream>
class Node{
    friend std::ostream &operator<<(std::ostream &os, const Node & n);
    public:
        Node(const int i = -1);
    private:
        Node * next;
        int value;
    friend class List;

};
#endif

Then I defined the methods in Node.cpp:

#include "Node.h"
using namespace std;

Node::Node(const int i):value(i), next(NULL){}

ostream& operator <<(ostream & os, const Node& n){
    return os<<"value : "<<n.value<<endl;
}

lastly, I have a test.cpp file to check the preprocessor:

#include "Node.h"
//#include <iostream>
using namespace std;

int main(){
    Node * n = new Node;
    cout<<*n;
}

however, when I tried to compile with gcc, I got the following error:

/home/xuan/lib/singleLinkedList/test.cpp:6:‘Node::Node(int)’undefined reference

like image 707
Xuan Zhou Avatar asked Jan 24 '26 02:01

Xuan Zhou


1 Answers

Given your files, when I run:

$ g++ test.cpp
/tmp/ccM7wRNZ.o:test.cpp:(.text+0x2c): undefined reference to `Node::Node(int)'
/tmp/ccM7wRNZ.o:test.cpp:(.text+0x44): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Node const&)'
/usr/lib/gcc/i686-pc-cygwin/4.5.3/../../../../i686-pc-cygwin/bin/ld: /tmp/ccM7wRNZ.o: bad reloc address 0x0 in section `.ctors'
collect2: ld returned 1 exit status

... but if I run:

Simon@R12043 ~/dev/test/cpp
$ g++ test.cpp node.cpp

Simon@R12043 ~/dev/test/cpp
$

Thus, I think you are not including node.cpp among the files to be linked into the project. That is, it is the linker that is not finding the Node class.

like image 59
Simon Avatar answered Jan 25 '26 15:01

Simon



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!