在Linux中使用g ++导致未定义引用“Class :: Function”(collect2:error) [英] Using g++ in Linux mint causing undefined reference to 'Class::Function' (collect2: error)
本文介绍了在Linux中使用g ++导致未定义引用“Class :: Function”(collect2:error)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
同样,stoi和exit(0)都超出了stk.cpp的范围,我不知道为什么。
Also stoi and exit(0) are both out of scope in stk.cpp and I don't know why.
这里是main.cpp
Here is main.cpp
#include "stk.h"
int main()
{
cout << "REDACTED\n" << endl;
stk m;
m.startProg();
}
使用 g ++编译时, v main.cpp -o test
作为此错误的结果:
undefined reference to 'stk::startProg()'
collect2: error: ld returned 1 exit status
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
这里是stk.cpp中的startProg函数
And here is the startProg function in stk.cpp
int stk::startProg()
{
while (true)
{
string line = "\0";
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\n", 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.
推荐答案
问题是,你在创建可执行文件时不是链接stk.cpp中的代码。
The problem is that you are not linking the code from stk.cpp when creating the executable.
解决方案1:先编译.cpp文件,然后链接。
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
解决方案2:在一个步骤中编译和链接这两个文件。
Solution 2: Compile and link both files in one step.
g++ main.cpp stk.cpp -o test
这篇关于在Linux中使用g ++导致未定义引用“Class :: Function”(collect2:error)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文