Search code examples
c++header-filesundefined-reference

"undefined reference to 'A::A(int,int)': when creating an object of a class from an included header


I am trying to use an object from another file, but I keep getting an undefined reference error despite having included the appropriate header file. I am using Eclipse with the C++ CDT plugin on Linux.

The code looks something like the following:

A.cpp:

class A {
private:
    int i;
    int j;

public:
    A(int i1, int i2) {
        i = i1;
        j = i2;
    }

    int sum() {
        return (i+j);          
    }
};

a.h:

#ifndef A_H_
#define A_H_

class A {
public:
    A(int i1, int i2);
    int sum();
};
#endif

main.cpp:

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

int main() {
   A a(1,2); //undefined reference to 'A::A(int,int)'
   std::cout << a.sum(); //undefined reference to 'A::sum(void)'
   return 0;
}

Is this a problem with my syntax, or do I need to go digging around in the compiler?


Solution

  • The problem is that main.cpp sees only the definition of the class in the header a.h that does not contain definitions of the constructor and of the member function.

    in A.cpp these function are defined but by default they are defined as inline functions. So again main.cpp does not see their definitions.

    Take into account that according to the C++ Standard (3.2 One definition rule)

    6 There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then

    (6.1) — each definition of D shall consist of the same sequence of tokens; and

    So in A.cpp you should write

    #include "a.h"
    
    
      A::A(int i1, int i2) {
         i = i1;
         j = i2;
      }
    
      int A::sum() {
         return (i+j);          
      }
    

    Also a class definition shall be ended with a semicolon.