0

When I'm trying to compile my code, this message appears:

undefined reference to `N::my_class::do_something()'
collect2.exe: error: ld returned 1 exit status

What can I do?

my_class.cpp

#include "my_class.h" // header in local directory
#include <iostream> // header in standard library

using namespace N;
using namespace std;

void my_class::do_something()
{
    cout << "Doing something!" << endl;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    The function should be in the `namespace N`, at least the linker tries to find `N::my_class::do_something`, not `my_class::do_something`. – mch Oct 04 '22 at 21:13
  • [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Jesper Juhl Oct 05 '22 at 04:36

1 Answers1

1

This function definition

void my_class::do_something()
{
    cout << "Doing something!" << endl;
}

is placed in the global namespace. In fact it is equivalent to

void ::my_class::do_something()
{
    cout << "Doing something!" << endl;
}

But you need to define the function in the namespace N like for example

void N::my_class::do_something()
{
    cout << "Doing something!" << endl;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335