Undefined reference when using a function included in a header file [duplicate]

≯℡__Kan透↙ 提交于 2019-12-10 10:15:17

问题


I am experiencing something weird with my c++ source file or perhaps the compiler itself. It seems that when I attempt to compile the file, it hits me with a message -

undefined reference to "Basic_int_stack::Basic_int_stack()

undefined reference to "Basic_int_stack::Push(int)

Here is my code (I'm still a beginner so don't expect any crazy professional code )

Header file:

class Basic_int_stack
{
  public:
    // This part should be implementation independent.
    Basic_int_stack(); // constructor
    void push( int item );
    int pop();
    int top();
    int size();
    bool empty();

  private:
    // This part is implementation-dependant.
    static const int capacity = 10 ; // the array size
    int A[capacity] ; // the array.
    int top_index ; // this will index the top of the stack in the array
};

Implementations:

#include "basic_int_stack.h"// contains the declarations of the variables and functions.

Basic_int_stack::Basic_int_stack(){
  // the default constructor intitializes the private variables.
  top_index = -1; // top_index == -1 indicates the stack is empty.
}

void Basic_int_stack::push( int item ){
  top_index = top_index + 1;
  A[top_index] = item ;
}

int Basic_int_stack::top(){
  return A[top_index];
}

int Basic_int_stack::pop(){
  top_index = top_index - 1 ;
  return A[ top_index + 1 ];
}


bool Basic_int_stack::empty(){
  return top_index == -1 ;
}

int Basic_int_stack::size(){
    return top_index;
}

Main Function:

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


int main()
{
    int var;

    Basic_int_stack s1;
    while((std::cin >> var)>=0){
        s1.push(var);
    }
    return 0;
}

回答1:


This is happening because you're building your main file without building and linking your class implementation file as well. You need to adjust your build settings somehow.




回答2:


It is because you don't include Basic_int_stack.cpp when you complile.

Simplely speaking, when you encounter Undefined reference to xxx, it is a error generated by linker, when means the compliler can't find the implements. So you need check if you include the cpp file or dynamic library or static library.




回答3:


I faced the same problem. Finally I found a fix by including .cpp file in the main file.

#include "file_name.cpp" //In the main file


来源:https://stackoverflow.com/questions/28082675/undefined-reference-when-using-a-function-included-in-a-header-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!