2016-01-22 29 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

相關問題