g++: Undefined reference in very simple example

Please help with the following noob question about C++ and g++ compilation and linking. Essentially I have 2 classes in 2 different files, and can compile them but when I attempt to link, one class can't see the methods of the other, even though I am linking both. Order of object files does not help in this case.

The problem seems related to a non-default constructor that takes a parameter.

I have distilled and reproduced the problem in the following simple code:

File: a.cpp
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

class A
{
  public:
  int my_int;
    A(int i) {
      my_int = i;
      std::cout << "A";
    }
};


File: a.hpp
1
2
3
4
5
6
7
8
9
10
#ifndef __A_H_
#define __A_H_

class A
{
  public:
  A(int i);
};

#endif 


File: b.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

#include <a.hpp>

class B
{
  public:
  int my_int;
    B(int i) {
      my_int = i;
      A a(i);
      cout << "B\n";
    }
};

int main(int argc, char* argv[])
{
  B b(5);
  cout << "hello world: ";
  cout.flush();
  return 0;
}


Commands I use to build:
1
2
3
g++ -c -I. a.cpp
g++ -c -I. b.cpp
g++ -o c_test a.o b.o


Alternately, I've tried each of these:
1
2
3
g++ -o c_test b.o a.o
g++ -I. -o c_test a.cpp b.cpp
g++ -I. -o c_test b.cpp a.cpp


Error I get in any of above link scenarios:
1
2
3
b.o: In function `B::B(int)':
b.cpp:(.text._ZN1BC1Ei[B::B(int)]+0x1c): undefined reference to `A::A(int)'
collect2: ld returned 1 exit status


Thanks in advance for any insight.
Last edited on
You have two definitions of class A and both are different. I think it should be more like this:

a.hpp
1
2
3
4
5
6
7
8
9
10
11
#ifndef __A_H_
#define __A_H_

class A
{
	public:
	int my_int;
	A(int i);
};

#endif  


a.cpp
1
2
3
4
5
6
7
8
9
#include "a.hpp" // use same class definition everywhere by including it
#include <iostream>

// define only the class member functions in the .cpp file
A::A(int i) 
{
	my_int = i;
	std::cout << "A";
}

That may help.
I think the reason is that the compiler treats the function defined in class as inline, so the function symbol is not visible outside the file(a.cpp) by default.
To resolve the problem, you need to move the function definition out of the class A, or use compiler option -fkeep-inline-functions.

-fkeep-inline-functions
In C, emit static functions that are declared inline into the object file, even if the function has been inlined into all of its callers. This switch does not affect functions using the extern inline extension in GNU C90. In C++, emit any and all inline functions into the object file.
Last edited on
Topic archived. No new replies allowed.