user3645925
user3645925

Reputation: 121

Linker error, undefined reference, makefile issue?

I am compiling the following code using clang++ and the compiler keeps erroring out with undefined reference to anything in the Link class. I assumed the compiler must not be getting the link.cpp definitions for all of the functions and constructors in the cpp file but I don't know if its some kind of include error or a makefile error at this point. Also this makefile outputs as a.out but I tohught the -o flag should make it output as prog1.

main.cpp

#include <iostream>
#include <link.h>

int main (int argc, const char * argv[]) {

int i = 10;
while(i >= 0) {

    i--;
}    

Link test = new Link();

std::cout << "Hello, World!2\n";
return 42;
}

link.h

#ifndef LINK_H
#define LINK_H
#include <string>
using namespace std;

class Link {
private:
    string * value;
    Link * next;
public:
    Link(Link * nextLink, string * stringValue);
    ~Link();

}
#endif

link.cpp

#include <link.h>

Link::Link(Link * nextLink, string * stringValue) {

this.next = nextLink;
this.value = stringValue;
}

Link::~Link() {

delete value;
}

Link * Link::getNext() {

return next;
}

string * Link::getString() {

return value;
}

void Link::printAll() {

if (next != NULL) {
    cout << value << "\n" << next->printAll();
} else {
    cout << value << "\n";
}
}

makefile

main.o: main.cpp
    clang++ -g -Wall -Wextra main.cpp
link.o: link.cpp link.h
    clang++ -g -Wall -Wextra link.cpp link.h
all: main.o link.o
    clang++ -g -Wall -Wextra main.o link.o -o prog1

Upvotes: 0

Views: 3083

Answers (2)

aschepler
aschepler

Reputation: 72271

Use the -c flag to compile only without linking. The default make target is the one that comes first; you probably want this to be "all". Also, you should not pass a header file on the command line.

all: main.o link.o
    clang++ -g -Wall -Wextra main.o link.o -o prog1
main.o: main.cpp link.h
    clang++ -g -Wall -Wextra -c main.cpp
link.o: link.cpp link.h
    clang++ -g -Wall -Wextra -c link.cpp

Upvotes: 1

Jiahao Cai
Jiahao Cai

Reputation: 1250

I think it's because the include statement, change #include <link.h> to #include "link.h".

Also, you have some other errors, for example, you forget the semicolon after the definition of class Link.

Reference: What is the difference between #include < filename> and #include “filename”?

Upvotes: 0

Related Questions