2016-01-22 56 views
0

stoi和exit(0)都在stk.cpp的范围之外,我不知道为什么。在Linux mint中使用g ++导致对'Class :: Function'(collect2:error)的未定义引用

这里的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函数

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

格式化失败了我,假设所有的括号都是正确的。

+2

当你编译'main.cpp'时,你没有链接'stk.o'。 – user657267

+0

偏题:谨慎使用'exit(0);'。这个程序相对简单,所以在这里是安全的,但[退出]像杀手斧头一样杀死程序。](http://en.cppreference.com/w/c/program/exit)破坏者不会被打电话,资源可能不会被收回,像这样的坏事。 – user4581301

回答

2

问题是,你是而不是链接创建可执行文件时从stk.cpp代码。

解决方案1:首先编译.cpp文件,然后链接。

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

解决方案2:一步编译并链接两个文件。

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

非常好,我解决了我的问题是你在说什么,除了我没有使用g ++ -std = C++ 11 – Bridger

相关问题