Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c++ - Using g++ in Linux mint causing undefined reference to 'Class::Function' (collect2: error)

Also stoi and exit(0) are both out of scope in stk.cpp and I don't know why.

Here is main.cpp

#include "stk.h"

int main()
{
    cout << "REDACTED
" << endl;
    stk m;
    m.startProg();

}

Upon compiling this with g++ -v main.cpp -o test as results in this error:

undefined reference to 'stk::startProg()'
collect2: error: ld returned 1 exit status

And here is stk.h

#ifndef STK_H
#define STK_H

#include <iostream>
#include <string>
#include "stdio.h"

using namespace std;


class stk
{
    struct node
    {
        int data;
        node * next;
    };
    node *head;

    public:
        stk()
        {
            head = NULL;
        }
        int push(int val);
        int pop();
        int display();
        int reverse(node * temp);
        void insertAtBottom(int tVal, node * temp);
        bool isEmpty();
        int startProg();
    private:
};

#endif

And here is the startProg function in stk.cpp

    int stk::startProg()
 {
    while (true)
    {
        string line = "";
        getline(cin, line);

        if (0 == line.compare(0,4, "push"))
        {
            int val = 0;
            val = stoi(line.substr(5));
            push(val);
        }
        else if(0 == line.compare (0,3, "pop"))
        {
            pop();
        }
        else if (0 == line.compare(0,7, "isempty"))
        {
            printf ("%s
", isEmpty() ? "true" : "false");
        }
        else if (0 == line.compare(0,7, "reverse"))
        {
            node * top = NULL;
            reverse(top);

        }
        else if (0 == line.compare(0,7, "display"))
        {
            display();
        }
        else if (0 == line.compare(0,4, "quit"))
        {
            exit(0);
        }

Formatting failed me, assume all brackets are correct.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you are not linking the code from stk.cpp when creating the executable.

Solution 1: Compile the .cpp files first and then link.

g++ -c main.cpp
g++ -c stk.cpp
g++ main.o stk.o -o test

Solution 2: Compile and link both files in one step.

g++ main.cpp stk.cpp -o test

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...