【问题标题】:Undefined References and Segmentation Faults未定义的引用和分段错误
【发布时间】:2012-05-25 14:46:07
【问题描述】:

好的,我正在编写一个程序,它使用几个不同的类,包括链接排序列表和二叉搜索树/节点类。当我在 Visual Studio 中编译时,它运行时完全没有任何问题,100% 流畅,并且我已经在那里完全调试了它,没有出现任何错误。但是,当我将它放入 Unix 中时,我必须将其打开,然后用 g++ 对其进行测试,一切都变得糟糕透顶。如果我尝试访问的不仅仅是二叉树的根,我会得到一个“分段错误”。

当我使用命令“g++ main.cpp”时,我看到了几十个对其他类的成员函数的“未定义引用”。现在,我确实拥有所有必要的#include 语句,以及使用“#ifndef/#define/#endif”语句。唯一给我带来问题的两个类是 Employee 和 SearchTreeNode 类。以下是这两个以及主要的:

    #include "LinkedSortedList.h"
    #include "LinkedNode.h"
    #include "Employee.h"
    #include "SearchTreeNode.h"
    #include <string>
    #include <ostream>
    #include <iostream>
    #include <fstream>

    using namespace std;

    int main() {

LinkedSortedList<Employee> mylist;  //create the LSL
SearchTree mytree;                  //create the BST

int searchCount = 0; //occasionally used to count recursive calls to function
bool _continue = true;
char command;

do{

    cout << "\nEnter your command: \n" << endl;
    cout << "(I)nsert\n(F)ind Employee from ID\n(D)elete Employee from ID\n(L)ast Name Search\n(S)ave to file\n(R)ead from file\n(Q)uit" << endl;

    cin >> command;

    if(command == 'I' || command == 'i'){
        //insert
        Employee* newEmployee = new Employee();
        newEmployee->create();
        mylist.insert(*newEmployee);
        mytree.insert(newEmployee);
        cout << "Employee Added\n----------\n" << endl;
        newEmployee->print();
        cout << "\n----------\n" << endl;
    }
    else if(command == 'L' || command == 'l'){
        //arbitrary pointer to undefined matches to be used in fetchAllMatches()
        LinkedSortedList<Employee>* matches;
        string name;
        cout << "Last Name to Search for: " << endl;
        cin >> name;
        Employee* search = new Employee();
        search->setLastName(name);

        int matchCount = mylist.fetchAllMatches(*search, matches, matchCount);
        cout << mylist.size() << " Records Searched.\n"<< matchCount << " Matches Found:" << endl;
        //Make sure that there is something to print to avoid errors
        if(matchCount > 0)
            matches->print();

    }
    else if(command == 'D' || command == 'd'){
        int IDnumber;
        cout << "Enter Employee ID to delete: " << endl;
        cin >> IDnumber;

        if(mytree.getRoot() != NULL) { // make sure there is a tree to search through
            Employee *x = mytree.find(IDnumber, searchCount, mytree.getRoot());

            if(x->getAddress() != "null"){
                mylist.remove(*x);
                mytree.remove(x->getId());
                cout << "\n" << x << "\n---------\n" << "File Deleted" << endl;
            }

        } else {
            cout << "Tree is empty" << endl;
        }
    }
    else if(command == 'F' || command == 'f'){
        int IDnumber;
        cout << "Enter Employee ID to find: " << endl;
        cin >> IDnumber;
        searchCount = 0;
        if(mytree.getRoot() != NULL) { // make sure there is a tree to search through
            Employee* x = mytree.find(IDnumber, searchCount, mytree.getRoot());

            if(x->getAddress() != "null"){
                    cout << "\n" << *x << "\n" << endl;
            } else {
                cout << "Employee not found!" << endl;
            }

        } else {
            cout << "Tree is empty" << endl;
        }
    }
    else if(command == 'S' || command == 's'){
        string file;
        cout << "Write Database to File Name: " << endl;
        cin >> file;
        mylist.printToFile(file, mylist);
    }
    else if(command == 'T' || command == 't'){
        mytree.print(mytree.getRoot());
    }
    else if(command == 'R' || command == 'r'){
        //read
        if(mylist.size() > 0) {
            mylist.clear();
            mytree.clearTree(mytree);
        }
        string line;
        string file;
        int intLine;
        cout << "File Name: " << endl;
        cin >> file;
        ifstream myfile(file.c_str());
        if (myfile.is_open())
        {
            getline (myfile,line);
            if(line != "<Records>"){
                cout << "Not a database file." << endl;
            }
            //make sure it's still ok
            while ( myfile.good() )
            {

                getline(myfile, line);
                if(line != "<END>"){

                    Employee* newEmployee = new Employee();

                    for(int i = 0; i < 10; i++){
                        switch (i){

                        case 0:

                            newEmployee->setLastName(line);
                            break;
                        case 1:
                            getline(myfile, line);
                            newEmployee->setFirstName(line);
                            break;
                        case 2:
                            myfile >> intLine;
                            newEmployee->setId(intLine);
                            break;
                        case 3:
                            myfile >> intLine;
                            myfile.get();
                            newEmployee->setSalary(intLine);
                            break;
                        case 4:
                            getline(myfile, line);
                            newEmployee->setDept(line);
                            break;
                        case 5:
                            getline(myfile, line);
                            newEmployee->setPhone(line);
                            break;
                        case 6:
                            getline(myfile, line);
                            newEmployee->setAddress(line);
                            break;
                        case 7:
                            getline(myfile, line);
                            newEmployee->setHireDate(line);
                            break;
                        case 8:
                            getline(myfile, line);
                            newEmployee->setEmail(line);
                            break;
                        case 9:
                            getline(myfile, line);//eat the dashes
                            break;
                        }

                    }
                    mylist.insert(*newEmployee);
                    mytree.insert(newEmployee);
                }
                else {
                    myfile.close();
                }
            }

        }
        else cout << "Unable to open file";     
    }
    else if(command == 'Q' || command == 'q'){
        return 0;
    }
    else if(command == 'P' || command == 'p'){
        mylist.print();
    }
}
while(_continue);

return 0;
}






    #include <iostream>
    using namespace std;



    #ifndef _EmployeeClass_
    #define _EmployeeClass_


    class Employee {

    public:

Employee(){
    firstName;
    lastName;
    department;
    email;
    dateHired;
    phoneNumber;
    homeAddress;
    employeeID = 0;
    salary = 0;

    //this->create();
}

Employee(string last, string first, int ID, int _salary, string dept, string phone, 
    string address, string hireDate, string _email){

        lastName = last;
        firstName = first;
        employeeID = ID;
        salary = _salary;
        department = dept;
        phoneNumber = phone;
        homeAddress = address;
        dateHired = hireDate;
        email = _email;

        employeeCount++;
}

void create();
//list of getter functions to return private variables, preventing direct access.
int getId();
int getSalary();
string getFirstName();
string getLastName();
string getDept();
string getHireDate();
string getEmail();
string getAddress();
string getPhone();

friend bool operator!= (Employee &x, Employee &y);
friend bool operator== (Employee &x, Employee &y);  
friend bool operator<= (Employee &x, Employee &y);
friend bool operator>= (Employee &x, Employee &y);
friend bool operator< (Employee &x, Employee &y);
friend bool operator> (Employee &x, Employee &y);

friend ostream& operator<<(ostream& output, Employee& x);
void print();

//list of setter functions to set values for the private variables, without allowing direct access.
void setPhone(string phone);
void setId(int ID);
void setSalary(int salary);
void setFirstName(string name);
void setLastName(string surname);
void setDept(string dept);
void setHireDate(string hireDate);
void setEmail(string email);
void setAddress(string address);

    private:

//private member variables dependant on input for each individual object
string firstName;
string lastName;
string department;
string email;
string dateHired;
string homeAddress;
string phoneNumber;
int employeeID;
int salary;

int employeeCount;

    };

    #endif

这是员工类:

    #include <iostream>
    #include "Employee.h"


    #ifndef _SearchTreeNodeClass_
    #define _SearchTreeNodeClass_




    //this class makes a binary search tree of "search tree nodes" which contain 3                         pointers:
    //left: points to left child (value always less than node)
    //right: points to right child (value always greater than node)
    //data: points to an Employee object in memory.
    using namespace std;

    class SearchTreeNode
    {
    private:
SearchTreeNode( Employee* D,SearchTreeNode* L = NULL, SearchTreeNode* R = NULL )    // constructor
{ 
    data = D;
    left = L;  
    right = R; 
};
int         count;
Employee*   data;                           // node data
SearchTreeNode* left;                       // pointer to the left subSearchTree
SearchTreeNode* right;                      // pointer to the right subSearchTree

friend class SearchTree;                // give SearchTree complete access
    };
    #endif

    #ifndef _SearchTreeClass_
    #define _SearchTreeClass_


    using namespace std;

    class SearchTree
    {        
    public:
SearchTree();                           
virtual ~SearchTree();                  
SearchTree( const SearchTree& );        
SearchTree& operator=( SearchTree& );   
SearchTreeNode* getRoot();
SearchTreeNode* find(int, SearchTreeNode*);
Employee* find(int, int, SearchTreeNode* ); 
void insert( Employee* );               
void print();   
void destroy( SearchTreeNode* );        
void print( SearchTreeNode* );
void clearTree( SearchTree& );
void inorder( SearchTreeNode* );
void remove( int x );
    private:
SearchTreeNode* root;                       // pointer to the root of the search SearchTree                     
SearchTreeNode* copy( SearchTreeNode* );
void insert( SearchTreeNode*& root, Employee* );

    };
    #endif

【问题讨论】:

  • 回答会很有帮助:/
  • 好吧,你没有付出太多的努力。也许阅读sscce.org 会有所帮助。
  • 真的......我想问题的确切代码段以及问题的极端具体示例还不够。我的错。
  • 如果您真的相信是这样的,那么为什么您没有收到任何有用的回复?
  • 我已经搜索了一个多小时。如果我在其他地方通过修复程序准确地描述了这个问题,我就不会费心发帖了。与我的问题有关的唯一其他帖子要么是 A)缺乏“有用的回应”,B)完全没有答案,要么 C)一个非常简单的版本。

标签: c++ g++ segmentation-fault undefined-reference


【解决方案1】:

分段错误 每当您尝试读取或写入无效的内存地址时都会出现错误。这可能有很多原因 - 请查看 here 获取一些示例。

未定义的引用错误发生在您无法链接所需的库和/或目标文件时。从简单地使用 g++ main.cpp 开始,您既没有指定其他源文件也没有指定任何链接所需的库。

就像@Ray 上面所说的,当直接在命令行上编译时,你必须自己提供包含和链接目录,这就是我们通常有一个 Makefile 的原因。使用正确制作的 Makefile 比直接调用编译器要好,因为 make 检查哪些源文件发生了更改,调用编译器来重建所需的文件而不是所有文件(这在你的项目中会产生很大的不同)很大!)。

如果您对 Makefile 没有太多经验,我建议您使用 CMake。它是一个为您制作 makefile 的构建系统。好在它甚至是多平台的,因此使用相同的 CMakeLists.txt 文件,您可以为 Windows 或 Linux 生成 makefile,而且语法非常简单。

如果你告诉我你拥有的所有源文件和你可能使用的最终库,我可以给你一个准确的 CMakeLists.txt 示例,它应该为你编译所有东西,但它可以很简单如下(根据您的包含,我假设您的源文件将是 main.cppLinkedSortedList.cppLinkedNode.cpp、Employee.cpp 和 SearchTreeNode.cpp):

cmake_minimum_required (VERSION 2.6)

project (employee_manager CXX)

set (SOURCES
  main.cpp
  LinkedSortedList.cpp
  LinkedNode.cpp
  Employee.cpp
  SearchTreeNode.cpp
  )

add_executable (employee_manager ${SOURCES})

您应该在源代码目录中创建此文件。要将编译输出与源代码分开,您可以创建一个构建目录,在那里运行 CMake,并参考父目录中的 CMakeLists.txt 文件,它将为您构建 Makefile。从那里,你只需要调用常规的 make 来构建你的程序:

mkdir build
cd build
cmake ..
make

这会将您的可执行文件 employee_manager 放入 build 目录中。

【讨论】:

    【解决方案2】:

    您遇到的问题有很多可能的原因。想到的一个是当你在 Visual Studio 中编译时,你已经设置了包含路径——搜索头文件的路径。也有可能你没有在 Visual Studio 中设置,而是在你创建项目并从各个目录向项目中添加文件时,VS 默默地为你设置了它。

    使用 g++,您必须自己提供包含目录。 (如果您在 Linux 下使用了类似于 Visual Studio 的 IDE,那么这些包含目录将为您设置。因此,问题不在于 Windows 和 Linux 之间的区别,而是在执行许多操作的 IDE 中进行开发之间的区别在幕后使用命令行编译。)

    查看 g++ 的手册页。查看用于添加包含目录的 -I 选项和在链接期间用于库搜索的 -l 选项。 (您很可能需要 -I 选项。)

    鉴于您在 Windows 上取得了成功,我怀疑您的源代码有问题。唯一的另一种可能性是您使用了特定于 Visual Studio 的库函数,而 g++ 中没有。

    【讨论】:

    • 我使用的库函数只有 iostream、fstream、ostream 和 string。所有文件都在同一个目录中;我正在使用 makefile,但所有依赖项似乎都是正确的。我拥有的唯一包含语句是用于访问其成员函数/变量的必要类。
    • 对不起,我的意思是你的文件的头文件。它们都在同一个目录中吗?如果它们甚至在子目录中,那么您将需要 -I 选项。另一方面,如果您所有的头文件都在同一个目录中,那么您应该检查 iostream 等是否正确定位。错误是否与缺少您的函数或库函数的函数有关?也许您可以使用这些错误消息更新您的帖子(如果有很多,前 10 条左右就可以了)。
    • 至于makefile,一般都是手工制作的。他们很难做到正确。要尝试的一件事是将每个 C++ 文件编译成一个目标文件而不进行链接。即 g++ -c Employee.cpp 。 (当然,您应该打开警告。)如果您得到一个目标文件,那么您在上面发布的 Employee.cpp 没有任何问题。
    猜你喜欢
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多